#!/bin/sh
# $Id: pap,v 1.5 2002/05/15 14:17:13 rupi Exp $
# cups backend script for printing to AppleTalk printers via pap
# based on the cap backend-script found in CUPS Software Administrators Manual
# 
# see CUPS Software Programmers Manual for explanation of enviroment and
# arguments
# usage: pap job user title copies options [filename]
#
# netatalk commands were using
nbplkup=/usr/bin/nbplkup
pap=/usr/bin/pap
psf=/usr/sbin/psf

# Device discovery if no argument is given
# Explaination of Perl regex used here: ^\s+.. some whitespace characters at the 
# beginning of a line. Followed by some [^:] non-colon characters we want to remember.
if [ ${#} = 0 ]; then
	$nbplkup :LaserWriter |  perl -e 'while (<>) { /^\s+([^:]+):.+$/; \
		print "network pap \"$1\" \"AppleTalk LaserWriter\"\n"; }'
    exit 0
fi

# Collect copies
copies=${4}

# Extract AppleTalk nbpname from device uri
nbpname=`echo $DEVICE_URI | perl -e 'while(<>){ /^pap:\/\/(.+)\//; print $1;}'`

# 5 command-line arguments mean file is at STDIN, the 6th arg is the filename
file=${TMPDIR}/$$.prn
if [ ${#} = 5 ]; then
    # Get print file from stdin; copies have already been handled...
    copies=1
	# If we get data from stdin we have to delete tmpfiles ourself
	delete=1
    cat > ${file}
else
	file=$6
fi

# If the content-type is not postscript filter through psf
if [ "${CONTENT_TYPE}" != "application/postscript" ]; then
	filename=`/bin/basename ${file}`
	psfile="${TMPDIR}/${filename}.ps"

	${psf} < ${file} > ${psfile}
	
	# Remove tmpfile
	if [ ${delete} = 1 ]; then
		/bin/rm -f $file
	fi
	
	# Set filename to our new postscript-file and set delete true
	file=${psfile}
	delete=1
fi

# Now everything should be ok -- we can print the file
while [ $copies -gt 0 ]; do	
		# no error handling implemented now !
		${pap} -p "${nbpname}" $file
        copies=`expr $copies - 1`
done

# Remove any temporary files...
if [ ${delete} = 1 ]; then
	/bin/rm -f $file
fi

exit 0
