#! /bin/bash
#
# 'makebook.sh'
#
# - Rearranges a PostScript document for printing in booklet form.
# - Uses 'psbook' to rearrange page order, then 'psnup' for the 
#   reduction DIN A4 -> 2-up A5 format.
# - option "-p" allows to run "only" the conversion A4 -> 2-up A5.
# - The script inserts code for duplex printing with short-edge 
#   binding, which works _at least_ on the HP Laserjet series.
#
# -------------------------------------------------------------------
# Creation:  2000-04-19, JHa.
# Revisions: 
# 2001-04-15, more comments (JHa ;-)
# 2002-10-10, runs on Solaris, and with different program path (ME)
# 2003-02-19, added error checks; added cmd line switches; added 
#             use of wildcards on the command line (JHa)
# 2005-03-18, fix in checkfor() error message (JHa)
# -------------------------------------------------------------------
# Copyright (c) 2000...2005 Joerg Hau <joerg.hau(at)dplanet.ch>.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# -------------------------------------------------------------------

set -f

# subroutine to check for some required executables
# argument: (list of) programs to test for
# will exit with rc=1 if any program was not found
# 
function checkfor()
{
for i in $*; do
    PROG=`which $i`
    if [ $? != 0 ] ; then
	echo "'$i' command not found, exiting."
	exit 1
    fi
done
}

checkfor psbook psnup cat sed echo

# pre-set some variables ...
#
MODE="psbook"
OUTP="file"

# pase cmd line parameters
#
while true ; do
  case "$1" in 
    -p) MODE="cat" ; shift ;; 
    --) OUTP="&1"  ; shift ;;
    *)  break ;;
  esac
done

# if script is called w/o remaining arguments, give usage instructions
#
if [ -z $1 ] ; then 
	echo "Usage: ${0##*/} [-p] [--] file1.ps [file2.ps ...]"
	echo "Where  -p create 'only' 2-up pages (no booklet order)"
	echo "       -- writes to stdout" 
	echo "Default: create booklet and write to file (*.book.ps)"
	exit 1
fi

for fn in "$@" ; do  # for all files given as parameters
                     # ("$@" prevents trouble with whitespaces in fn)
         
    # check if $fn is accessible
    #
    if [ ! -f ${fn} ] ; then
        echo "*** Warning: '${fn}' is not accessible, skipping! ***"
        continue  
    fi
    
    $MODE $fn | psnup -2 | sed '2i\
<</Duplex true /Tumble true>> setpagedevice' > $$.tmp
    
    if [ $OUTP = "file" ] ; then 
      mv $$.tmp "${fn%.*}.book.ps"
    else
      cat $$.tmp && rm -f $$.tmp
    fi
done

exit 
