#! /bin/bash -

# H.A.Trujillo
# 13 Jun 13
# Last Change:     27 Feb 2016

help_text() {
    esc=$'\e'
    cat <<- EOT

	$esc[32m${0##*/}$esc[m
		Merge one or more pdf files using gs, to create a new
		(often smaller) pdf.

	    usage:  pdf2pdf   [-eE]  infile.pdf  [infile2.pdf ...]  outfile.pdf
	            pdf2pdf   [-eE]  -o outfile.pdf  infile1.pdf  [infile2.pdf ...]

	    notes:  input file list may also contain .ps files.

	    options:
	            -e	produce an encripted pdf
		    -E  read encrypted input  (will ask for a password)
	            -o  specify outfile
	            -h  produce this help message

	EOT
	exit
    }


echo ""

# process options
pw1=pw2=pw3=pw_opts=""
while [ _${1:0:1} == _- ]  ; do
    case $1 in 
	-e)	# encrypt the output
	    read -sp "	New Password: " pw1
	    echo ""
	    read -sp "	       Again: " pw2
	    echo ""
	    if [ "$pw1" == "$pw2" ] 
	      then
		if [[ $pw1 =~ \  ]] 
		  then 
		    echo " -> password can't contain spaces"
		  else
		    pw_opts="$pw_opts "'-sOwnerPassword=\  -sUserPassword='$pw1
		    shift
		fi
	      else
		echo " -> oops -- passwords don't match"
	    fi
	    ;;

	-E)	# encrypted input
	    read -sp " Passwd to open file: " pw3
	    echo ""
	    pw_opts="$pw_opts -sPDFPassword=$pw3"
	    shift
	    ;;

	-h) help_text
	    ;;

	-o) 	# specify the outfile among the options
	    outfile=$2
	    shift 2
	    infile=("$@")
	    ;;
    esac
done


if [ -z $outfile ] ; then
    if [ $# -lt 2 ] ; then
	echo "    no output file specified -- aborting"
	exit
    fi
    args=("$@")
    lastarg=$(( ${#args[@]} - 1 ))
    outfile=${args[$lastarg]}
    unset args[$lastarg]
    infile=("${args[@]}")
fi


if [ -e $outfile ] ; then
    printf "\n    overwrite ${outfile}? [n] "
    read 
    if [ "$REPLY" != y ] ; then exit 1 ; fi
fi


gs -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -sOutputFile="$outfile" \
	$pw_opts ${infile[@]}  \
    || {
	printf "\n ${0##*/}: Errors -- aborting \n" 
	rm -f "$outfile"
	exit 1
       }
exit

#  v1:   13 jun 13
#  v1.1  Sep 13	 - outfile = last arg when >2 arguments
#		 - quoting of filenames
#		 - checking before overwriting an outfile
#  v2	 6Mar15	 - output encryption, multiple flags
#  v2.1	 26feb16 - read encrypted input files
#  		

