#!/bin/sh -e
export PATH="$(dirname $(realpath $0)):$PATH"
export BLOGS="$(realpath blogs)"
export SRC="$(realpath src)"
export LAYOUTS="$(realpath share/layouts)"

usage()
{
  >&2 cat << USAGE
usage: blog -i LOG [-p POSTPROCESS_CMD] [-a EXTRACT_ARGS_CMD] [-l LAYOUT] [-t] [-f FILE_PATTERN]

options:

    -a EXTRACT_ARGS_CMD
        If provided, a shell command to extract arguments to the layout from the
        source files. The shell will be provided with a variable, POST_TITLE.

    -f FILE
        If provided, a pattern for the files to process. Default: *.

    -i LOG
        The name of the source directory under \$BLOGS where log posts live.

    -l LAYOUT
        If provided, the layout under \$LAYOUTS to use for the generated
        upphtml files. If not provided, uses the default layout.

    -p POSTPROCESS_CMD
        If provided, a shell command to post-process the source files into
        upphtml. The shell will be provided with a variable, POST_TITLE.

    -t
        If enabled, use filenames as post titles
USAGE
}

extract_args_cmd="head -n 0 | echo \"POST_TITLE=\\\"\${POST_TITLE}\\\"\""
file_pattern="*"
log_name=""
layout_name="default"
postprocess_cmd="echo"
use_filenames_for_titles=0

while getopts "a:f:i:l:p:t" opt
do
  case $opt in
    a)
      extract_args_cmd="$OPTARG"
      ;;
    f)
      file_pattern="$OPTARG"
      ;;
    i)
      log_name="$OPTARG"
      ;;
    l)
      layout_name="$OPTARG"
      ;;
    p)
      postprocess_cmd="$OPTARG"
      ;;
    t)
      use_filenames_for_titles=1
      ;;
  esac
done

if [ -z "${log_name}" ]
then
  usage
  exit 1
fi

if ! [ -d "${BLOGS}/${log_name}" ]
then
  >&2 echo "there is no directory '${input_log}' under ${BLOGS}. options: $(ls common)"
  usage
  exit 1
fi

layout="${LAYOUTS}/${layout_name}.layout.upphtml"
if [ "${layout_name}" = "default" ]
then
  layout_ext=""
else
  layout_ext=".${layout_name}"
fi
if ! [ -f "${layout}" ]
then
  echo >&2 "Warning: no layout found at $(basename "${LAYOUTS}")/${layout_name}.layout.upphtml"
fi

mkdir -p "${SRC}/${log_name}"

for entry in $(find -L "${BLOGS}/${log_name}" -type f -name "${file_pattern}")
do
  basename="$(basename "$entry")"
  name="${basename%\.*}"
  dest="${SRC}/${log_name}/${name}${layout_ext}.upphtml"
  if [ $use_filenames_for_titles -eq 1 ]
  then
    title="$name"
    cat "$entry" |  eval "POST_TITLE=\"${title}\" ${postprocess_cmd}" > "$dest"
  else
    title="$(grep --regexp "^# " --max-count 1 "$entry" | cut -c3-)"
    export POST_TITLE="$title"
    cat "$entry" | grep --regexp "^# " --invert-match | eval "$postprocess_cmd" > "$dest"
  fi
  cat "$entry" | eval "$extract_args_cmd" > "${dest}.args"
  echo "Processed ${entry#$(dirname ${BLOGS})/} to ${dest#$(dirname ${SRC})/}"
done
