#!/bin/sh

# render a zodiac page

zod_lib="$1"
proj="$2"
target="$3"
f="$4"

markdown_filter_cmd="awk -f $zod_lib/markdown.awk"

[ -f "$proj/helpers.awk" ] && helper_opts="$proj/helpers.awk"
[ -f "$proj/filters.config" ] && filter_opts="$proj/filters.config"
[ -f "$proj/global.meta" ] && global_meta_opts="$proj/global.meta"
[ -f "$proj/main.layout" ] && layout_opts="$proj/main.layout"

# Find the target directory if one must be created
subdir=${f%/*}
subdir=${subdir#$proj}
if [ "$subdir" ]; then
  destination="$target$subdir"
  mkdir -p "$destination"
else
  # There is no directory to create in target,
  # i.e. file is in the root of the project
  destination="$target"
fi

ext=${f##*.}
if [ $ext == "md" ] || [ $ext == "html" ]; then

  meta=${f%.$ext}.meta
  [ -f "$meta" ] && page_meta_opts="$meta"

  set -- -f "$zod_lib/render.awk"
  [ "$helper_opts" ] && set -- "$@" -f "$helper_opts"
  set -- "$@" -v markdown_filter_cmd="$markdown_filter_cmd" \
              "$filter_opts" \
              "$global_meta_opts" \
              "$page_meta_opts" \
              "$f" \
              "$layout_opts"

  page=${f##*/}
  page=${page%.$ext}.html

  awk "$@" > "$destination/$page"

else
  cp "$f" "$destination" # Copying a non-template file
fi