#!/usr/bin/env zsh

# https://pandoc.org/demo/pandoc.1.md
# https://eddieantonio.ca/blog/2015/12/18/authoring-manpages-in-markdown-with-pandoc/
# https://jeromebelleman.gitlab.io/posts/publishing/manpages/

0=${(%):-%x}
BASEDIR=${0:a:h:h}
TMPDIR=$BASEDIR/.tmp/buildman
[[ -d $TMPDIR ]] && command rm -rf $TMPDIR
mkdir -p $TMPDIR

sedi() {
  sed --version &> /dev/null && sed -i -- "$@" || sed -i "" "$@"
}

for manpage in $BASEDIR/man/*.md; do
  case ${manpage:t:r} in
    footer|example) continue ;;
  esac
  print "Building ${manpage:t:r} manpage..."
  [[ -d $BASEDIR/man/man1 ]] || mkdir -p $BASEDIR/man/man1

  mdfile=$TMPDIR/${manpage:t}.md
  cat ${manpage} > $mdfile
  print "" >> $mdfile
  cat $BASEDIR/man/footer.md >> $mdfile

  manfile=$BASEDIR/man/man1/${manpage:t:r}.1
  pandoc --standalone --to man ${mdfile} -o $manfile

  # strip pandoc version so that every manpage build doesn't need to
  # result in a new commit just b/c pandoc has a minor point release.
  pandoc_ver=$(pandoc -v | awk 'NR==1{print $2}')
  sedi "s/Pandoc $pandoc_ver/Pandoc/g" $manfile
done
