#!/bin/sh -e
#
# bookletize - convert a PDF to a fold-able booklet sized PDF
# print it double-sided and fold in the middle

main() {
  (
    command -v pdfinfo >/dev/null \
      && command -v pdflatex >/dev/null
  ) || {
    printf 'Missing required pdfinfo or pdflatex\n'
    return 1
  }

  pagecount=$(pdfinfo "$1" | awk '/^Pages/{ print $2+3 - ($2+3)%4; }')

  # create single fold booklet form in the working directory
  pdflatex -interaction=batchmode \
    '\documentclass{book}\
    \usepackage{pdfpages}\
    \begin{document}\
    \includepdf[pages=-,signature='${pagecount}',landscape]{'$1'}\
    \end{document}' >/dev/null 2>&1
}

main "$@"
