#!/bin/sh -e
export PATH="$(dirname $(realpath $0)):$PATH"

usage() {
	>&2 printf "usage: %s url [pattern]\\n" "$(basename "$0")"
	exit 1
}

test $# -lt 1 && usage

export SRC="$(realpath src)"
export PUBLIC="$(realpath public)"
export SHARE="$(realpath share)"
export LAYOUTS="$(realpath share/layouts)"
export DEFAULT_LAYOUT="${LAYOUTS}/default.layout.upphtml"
export OUT="$(realpath out)"

if ! test -f "${SRC}"/index.upphtml
then
	>&2 printf "no index.upphtml file found\\n"
	exit 1
fi

PATH_PATTERN="${2:-*}"
for t in $(find -L "${SRC}/" -type f -and -wholename "${PATH_PATTERN}" -and -name "*\.upp*" -and -not -name "*\.upp*\.*")
do
  basename="$(basename "$t")"
  ext="${basename##*upp}"

  basename_without_ext="${basename%\.upp${ext}}"
  penultimate_segment="${basename_without_ext##*\.}"
  if [ "$basename_without_ext" != "$penultimate_segment" ] && [ -f "${LAYOUTS}/${penultimate_segment}.layout.upphtml" ]
  then
    layout="${LAYOUTS}/${penultimate_segment}.layout.upphtml"
    name="${basename%\.${penultimate_segment}\.upp${ext}}"
  else
    layout="${DEFAULT_LAYOUT}"
    name="${basename%\.upp${ext}}"
  fi

  in_dir="$(dirname "$t")/"
  rel_dir="${in_dir#${SRC}/}"
  mkdir -p "${OUT}/${rel_dir}/"

  args="$( [ -f "${t}.args" ] && cat "${t}.args" || echo "" )"
  if [ "$(head -n 1 "${layout}")" = "#!" ]
  then
    >"${layout}.tmp" echo "
#!
${args}
$(tail -n +2 "${layout}")
"
  else
    >"${layout}.tmp" echo "
#!
${args}
#!
$(cat "${layout}")
"
  fi
  if [ "$ext" = "html" ]
  then
    pp "${layout}.tmp" "${t}" "${1}" > \
  		"${OUT}/${rel_dir}/${name}.${ext}"
	else
    pp "${t}" "${1}" > \
  		"${OUT}/${rel_dir}/${name}.${ext}"
  fi
  rm "${layout}.tmp"

  echo "Written ${OUT}/${rel_dir}${name}.${ext}"
done
