#!/bin/bash

COPIES="${1:-1}"
PDF="`xxd -p`"
PAGES=`xxd -p -r <<<"$PDF" | pdfinfo - | sed -nre 's/Pages:\s*(.*)/\1/p'`

if (( PAGES <= 2)); then
  : $(( COPIES = (COPIES + 1) / 2 ))
fi

xxd -p -r <<<"$PDF" |
case $PAGES in
  1) pdfjam --nup 2x1 --landscape --doublepagestwistodd\* true -o /dev/stdout /dev/stdin 1,'{}';;
  2) pdfjam --nup 2x1 --landscape --doublepagestwistodd\* true -o /dev/stdout /dev/stdin 1,2;;
  *) pdfbook -o /dev/stdout /dev/stdin;;
esac | pdfjoin -o /dev/stdout /dev/stdin `python -c "print(','.join(['-']*$COPIES))"`

