#!/bin/sh
#
# xman - open manual as PDF in zathura(1), while watching for changes
# dependencies: zathura | troff (heirloom-doctools) | ps2pdf (ghostscript) | entr | sponge (moreutils)
#
# ---
# source: https://github.com/phillbush/home/blob/master/bin/xman

# get roff file
case "$#" in
  1)
    if test -f "$1"; then
      man="$1"
    else
      man="$(man -w "$1")" || exit $?
    fi
    ;;
  2)
    man="$(man -ws "$1" "$2")" || exit $?
    ;;
  *)
    echo "usage: xman [[section] manual | file]" >&2
    exit 2
    ;;
esac

# man could have returned a list of files; get first only
man="${man%%
*}"

# get roff file format (man or mdoc)
case "$(<"${man}" sed -n '/^\.[^\\]/{p;q;}')" in
  .Dd* | .Dt*) fmt="mdoc" ;;
  *) fmt="man" ;;
esac

# create future pdf file
pdf="$(mktemp)" || exit $?
trap '
	rm -f "$pdf"
	jobs -p | xargs -r kill
' EXIT

# postpone opening pdf file until it is converted once
printf "%s\n" "${pdf}" | if entr -npz true; then
  exec zathura -- "${pdf}"
fi &
reader_pid="$!"

# convert manpage to pdf; rerun whenever manpage file changes
printf '%s\n' "${man}" | entr -nrs "
	{
		printf '.fp 5 CW DejaVuSansMono\n'
		cat \"${man}\"
	} |
	eqn |
	tbl |
	troff -\"${fmt}\" - |
	dpost |
	ps2pdf -sPAPERSIZE=letter - |
	sponge \"${pdf}\"
" &
troff_pid="$!"

# wait for pdf reader to close; then terminate troff conversor
wait "${reader_pid}"
status="$?"
kill "${troff_pid}"
exit "${status}"
