#!/bin/sh

share="/usr/share/man"
localshare="/usr/local/man"
mandoc="mandoc -c -mdoc -O paper=a4 -T pdf"

if [ -t 0 ]; then
  if [ ${#} -ne 2 ]; then
    echo "Usage: ${0} <section> <manpage>" >/dev/stderr
    echo >/dev/stderr
    echo "It is assumed the manpage can be found within ${share} or within ${localshare} as a gzipped file." >/dev/stderr
    echo "${0} can also be used as a filter, it will then run \"${mandoc}\"." >/dev/stderr
    exit 69
  fi

  section=${1}
  manpage=${2}

  input1="${share}/man${section}/${manpage}.${section}.gz"
  input2="${localshare}/man${section}/${manpage}.${section}.gz"

  input=${input1}

  if [ ! -r ${input} ]; then
    input=${input2}

    if [ ! -r ${input} ]; then
      echo "${0}: unable to read ${input1} nor ${input2}" >/dev/stderr
      exit 66
    fi
  fi

  output="${manpage}.${section}.pdf"

  gzcat ${input} | ${mandoc} > ${output}
else
  ${mandoc}
fi

# EOF
