#! /bin/sh

#	$Id: apsfilter,v 1.4 1999/03/01 16:02:32 andreas Exp $

################################################################################
#
#	apsfilter 5.0.1 - Line Printer Input Filter
#	-------------------------------------------
#
#	Copyright by Andreas Klemm <andreas@klemm.gtn.com>
#		Copyright 1993, 1994, 1995, 1996, 1997, 1998, 1999
#
#	You are permitted to modify and distribute apsfilter in the
#	terms of the GNU Public License (GPL) see below.
#
#	For Unix Systems With BSD Alike Print Mechanism (lpd, /etc/printcap)
#
#	Supports The Following File Types:
#
#		Ascii, DVI, PS, Data (PCL,...), GIFF, TIFF, PBM, 
#		Sun Raster, X11 Bitmap, HTML, PDF
#
#	Supports The Following Compression Types:
#
#		bzip2, gzip, compress, freeze, pack
#
#	and various contributors
#
################################################################################

################################################################################
# Only for debugging purposes. If you comment out the line set -x
# (removing the '#' at the beginning of the line, then you can find very
# useful debugging output in the printers logfile 
# (see /etc/printcap definition lf=/var/spool/.../log)
# Please note: this 'log'-file has to be present in the directory, if it's
# not present, then create it using the command
#	:>log
################################################################################

#set -x

# Only for experts:
# Do we have a remote printer (printer directly connected to ethernet) ???
# Then please make a reasonable entry in /etc/printcap manually and 
# activate this line:

#REMOTE_PRINTER=True

# we don't want to waste paper when debugging printing ...
#
#	the "Save the Rain Forest Feature" ;-)
#

#PRINT_TO_FILE="True"

################################################################################
#
#			C O P Y R I G H T 
#
################################################################################
#
#
# You are permitted to use this script in the terms of the 
#
# 		    GNU GENERAL PUBLIC LICENSE
# 		       Version 2, June 1991
# 
#
#  Copyright (C) 1989, 1991 Free Software Foundation, Inc.
#                           675 Mass Ave, Cambridge, MA 02139, USA
#  Everyone is permitted to copy and distribute verbatim copies
#  of this license document, but changing it is not allowed.

################################################################################
#
# remember the command line in case we need to call ourselves recursively
#
################################################################################

APS_CMD="$0 $@"

################################################################################
#
# Grab apsfilters basedir from /etc/printcap
#
################################################################################

APS_BASEDIR=`grep APS_BASEDIR /etc/printcap | cut -d ':' -f 2`
export APS_BASEDIR

################################################################################
#\	evaluate command line arguments that are given to the
# \	input filter 
#  \  
#   >	apsfilter [-c] -wwidth -llength -iindent -n login -h host acct-file     
#  /
# /	defaults: width=80, length=66, indent=0
#/
#       don't rely on order, use option letters to identify options.
#       in case you wonder: the dummy string in the echo command is
#       there so that echo doesn't treat $1 as an option.
#
################################################################################

while [ -n "$1" ]; do
  if [ `echo dummy $1 | awk '{ print substr($2,1,1) }'` = "-" ]; then
    opt=`echo dummy $1 | awk '{ print substr($2,2,1) }'`
    val=`echo dummy $1 | awk '{ print substr($2,3) }'`
    if [ -z "$val" ]; then
      val=$2
      shift
    fi
    case "$opt" in
      w) WIDTH=$val;;
      l) LENGTH=$val;;
      i) INDENT=$val;;
      n) LOGINNAME=$val;;
      h) HOST=$val;;
    esac
  else
    ACCTFILE=$1
  fi
  shift
done

if [ -z "$WIDTH" -o "$WIDTH" = "0" ]; then WIDTH=80; fi
if [ -z "$LENGTH" ]; then LENGTH=66; fi
if [ -z "$INDENT" ]; then INDENT=0; fi

# get users home directory...
# needed in print_dvi to look for ps pictures automatically
HOME_DIR=`grep "^$LOGINNAME:" /etc/passwd|cut -d ':' -f 6|uniq`

################################################################################
#
# NEW: auto configuration
#
################################################################################
#
# if apsfilter is called as:
#
#	aps-djet500-a4-{auto,ascii,raw}-{color,mono}
#	$1   $2     $3      $4          $5
#	then we get printer type and papersize from the apsfilter call itself
#	after some trickery with cut and sed (where cut is hopefully part of
#	every Unix disrtibution, otherwise get the gnu version of cut
#	METHOD=auto	enables filetype auto recognition
#	METHOD=ascii	force printing method print ascii
#	METHOD=raw	write to print device unfiltered ....
#	COLOR=color	use color-postscript
# 	COLOR=mono	transform color to b&w postscript... so one is
# 			able to save colored pens on a colorprinter
SYSTEM=`uname -s`

case $SYSTEM in
	*BSD*|*bsd*)
		set -- `basename $0 | cut -f1 -d\ | sed -e 's/-/ /g'` ;;
	*)
		set -- `basename $0 | cut -d\  -f1 - | sed -e 's/-/ /g'` ;;
esac

LABEL=$1; PRINTER=$2; PAPERSIZE=$3; METHOD=$4; COLOR=$5

case $LABEL in
	*aps)	# jup, seems to be that we are installed properly
		;;
	*)	# unknown filter - therefore EXIT APSFILTER
		echo "$1 wrong input filter" 2>&1
		exit 0 ;;
esac

case $COLOR in
	color)	# color-mode! set some options so color makes it to
		# the postscript-printer!
		PNMTOPS="pnmtops"
		RAS2PS_OPTS="-C"
		DJPEG_OPTS="-colors 256"
		;;

	*)	# mono-printer! Unset all color-dependent flags
		PNMTOPS="( ppmtopgm | pnmtops )"
		DJPEG_OPTS="-grayscale"
		;;
esac

################################################################################
# User customization:
# ------------------
# - every time we read the systems global apsfilterrc
#   to get sane defaults. Perhaps we need that in the future...
# - Then the user gets a change to overwrite the systems defaults
#   with it's own copy of /etc/apsfilterrc in his HOME directory...
################################################################################

# First this ... for now it's optional, but this might be a must
# in the future ..

if [ -f /etc/apsfilterrc ]; then
	. /etc/apsfilterrc
fi

# WARNING:
# This user custom configuration file is indeed a shell script
# It runs with the Permissions of the lpd printer daemon.
# This might be root Permissions, so this is a big security whole.
# Default is, NOT to permit users to configure apsfilter by
# their own $HOME/.apsfilterrc file.
# You must be root to set INSECURE to True in /etc/apsfilterrc 
# to allow user custom config files !!!

if [ "$INSECURE" = "True" ]; then

	if [ -f $HOME_DIR/.apsfilterrc ]; then
		. $HOME_DIR/.apsfilterrc
	fi

fi

################################################################################
#
# ENVIRONMENT SECTION - Global settings - in most cases nothing to change here
#
################################################################################
#
# Reference of Shell Variables:
# -----------------------------
#
#	(1)  MAILX 		<- Your mailx program (can handle -s "Subject"
#				   option)
#
#	(2)  DVIPS_RESOL_DorP	<- default set to -D for Thomas Essers dvips
#				   in his famous teTeX 0.3 release
#
#	(3)  DVIPS_OPTS		<- options for dvips
#				   some options are defaults some are computed
#				   automatically. Depends on the following
#				   variables:
#					PRINTER, PAPERSIZE
#	(4)  PRINT_PS		<- The print ps command ...
#
################################################################################

################################################################################
#
# READ GLOBAL ENVIRONMENT from GLOBAL.sh
#
################################################################################

. $APS_BASEDIR/global/GLOBAL.sh

#-------------------------------------------------------------------------------
#
# (1)  MAILX - your favourite mail program that understands "-s" (except elm !)
#      
#	typical Linux problems: /bin/mail is often a symlink to elm which
#	doesn't work since it misses the Mail folder directory, etc ....
#	Use the mailx program instead. Another advantage of mailx is, that
#	you can give a Subject with -s on the command line.
#	SunOS 4.1.X, Solaris 1 note: I think there is a program "Mail" which does
#	the job.
#
#-------------------------------------------------------------------------------

case $SYSTEM in
	*BSD*|*bsd*)		MAILX=Mail	;;
	Linux|linux)		MAILX=mailx	;;
	Solaris|solaris)	MAILX=Mail	;;
	Sun*|sun*)		MAILX=Mail	;;
	*)			MAILX=mailx	;;
esac

#-------------------------------------------------------------------------------
#
# (2)	DVIPS Resolution command line switch hacking *sigh*
#
#-------------------------------------------------------------------------------

# If nothing is set by /etc/apsfilterrc or $HOME/.apsfilterrc
# then default to -P, since this is the one needed for dvips
# that comes with Slackware's dvips.

if [ -z "$DVIPS_RESOL_DorP" ]; then
	
	# if nothing else is set I go with Thomas Essers teTeX ;-)
	DVIPS_RESOL_DorP=-D
fi


#-------------------------------------------------------------------------------
#
# (3) OPTIONS for dvips - DVIPS_OPTS
#
#		-M don't create fonts automatically using MakeTeXPK
#		   since there is a bug in it causing apsfilter to exit
#		   after creating the first missing Font.
#		-q quiet mode
#		-r print last page first
#		-t papertype
#			(look known formats in the config file config.ps
#			 on Linux Slackware usually in /usr/TeX/lib/tex/ps)
#		-D (or -P) num horizontal + vertical resolution in dpi 
#		   or:	-X num horizontal resolution in dpi 
#			-Y num vertical   resolution in dpi 
#		-Z compress bitmap fonts
#		   usually only when resolution is >= 400
#
#-------------------------------------------------------------------------------

case $PRINTER in
	PS_300dpi)		DVIPS_OPTS="-q $DVIPS_RESOL_DorP 300 -Z"     ;;
	PS_400dpi)		DVIPS_OPTS="-q $DVIPS_RESOL_DorP 400"        ;;
	PS_600dpi)		DVIPS_OPTS="-q $DVIPS_RESOL_DorP 600"        ;;
	PS_800dpi)		DVIPS_OPTS="-q $DVIPS_RESOL_DorP 600"        ;;
	cdj*|*desk*|djet*)	DVIPS_OPTS="-q $DVIPS_RESOL_DorP 300 -r -Z"  ;;
	ljet4l)			DVIPS_OPTS="-q $DVIPS_RESOL_DorP 300"        ;;
	ljet4)			DVIPS_OPTS="-q $DVIPS_RESOL_DorP 600 -Z"     ;;
	laserjet|ljet[23]*)	DVIPS_OPTS="-q $DVIPS_RESOL_DorP 300 -Z"     ;;
	paintjet|pj*)		DVIPS_OPTS="-q $DVIPS_RESOL_DorP 300"        ;;
	necp6)			DVIPS_OPTS="-q $DVIPS_RESOL_DorP 360"        ;;
	bj200|escp2|st800)	DVIPS_OPTS="-q $DVIPS_RESOL_DorP 360 -r"     ;;
	stcolor)		DVIPS_OPTS="-q $DVIPS_RESOL_DorP 360 -r"     ;;
	epson)			DVIPS_OPTS="-q -P360x180 -r"                 ;;
	bj10e)			DVIPS_OPTS="-q $DVIPS_RESOL_DorP 300 -r"     ;;
	*)			DVIPS_OPTS="-q $DVIPS_RESOL_DorP 300 -r"     ;;
esac

case $PAPERSIZE in
	letter|legal|ledger)	DVIPS_OPTS="$DVIPS_OPTS -t $PAPERSIZE"	;;
	a3)			DVIPS_OPTS="$DVIPS_OPTS -t A3"		;;
	a4)			DVIPS_OPTS="$DVIPS_OPTS -t A4"		;;
	*)			DVIPS_OPTS="$DVIPS_OPTS -t letter"	;;
esac

#-------------------------------------------------------------------------------
#
# (4) OUR COMPLETE PRINT_PS COMMAND
#
#	This shortens the print_xxx() functions,
#	that use gs as the final filter.
#	Now they all pipe through $PRINT_PS, which includes
#	the proper call of gs including all necessary options.
#
#-------------------------------------------------------------------------------

case $PRINTER in
	ljet4l)		# We can now act like a ljet4
			PRINTER=ljet4 ;;
	*)		;;
esac

case $PRINTER in

	PS_*dpi)
		# our printer is a PS printer...	
		PRINT_PS="cat -" ;;

	uniprint)
			PRINT_PS="	gs				\
					-q				\
					@${UP_PROFILE}			\
					-sOutputFile=-			\
					-				"
	;;

	*)	# we have a nice non ps printer
		if [ -z "$GS_RESOL" ]
		then
			# default is _not_ to fiddle around with
			# ghostscripts printer driver resolution
			PRINT_PS="	gs				\
					-q				\
					-sDEVICE=${PRINTER}		\
					-sPAPERSIZE=${PAPERSIZE}	\
					-dNOPAUSE			\
					-dSAFER				\
					-sOutputFile=-			\
		    			${GS_FEATURES}			\
					${PS_INIT}			\
					-				"
		else
			# if we urgently need another resolution
			# then we use it (selectable in /etc/apsfilterrc
			# or in $HOME/apsfilterrc)
			PRINT_PS="	gs				\
					-q				\
					-sDEVICE=${PRINTER}		\
					-r${GS_RESOL}			\
					-sPAPERSIZE=${PAPERSIZE}	\
					-dNOPAUSE			\
					-dSAFER				\
					-sOutputFile=-			\
		    			${GS_FEATURES}			\
					${PS_INIT}			\
					-				"
		fi
		;;
esac

if [ "$PRINT_TO_FILE" = "True" ]; then
	PRINT_PS="(cat 1> /tmp/aps_out.$$)"
fi

if [ "$REMOTE_PRINTER" = "True" ]; then
	PRINT_PS="$PRINT_PS | lpr -Premote"
fi

################################################################################
#####
##### S h e l l  -  F u n c t i o n s
#####
################################################################################

#===============================================================================
# print xfig files
#===============================================================================

print_fig()
{
	cat ${APS_HEADER} - | fig2dev -Lps -P -c | eval $PRINT_PS 
}

#===============================================================================
# print PBM / PNM pictures
#===============================================================================

print_pnm()
{
	cat ${APS_HEADER} - | eval $PNMTOPS | eval $PRINT_PS 
}


#===============================================================================
# print TIFF pictures
#===============================================================================

print_tiff()
{
	cat ${APS_HEADER} - | tifftopnm | eval $PNMTOPS | eval $PRINT_PS 
}

#===============================================================================
# print JPEG pictures
#===============================================================================

print_jpeg()
{
	cat ${APS_HEADER} - | djpeg $DJPEG_OPTS | eval $PNMTOPS | eval $PRINT_PS
}

#===============================================================================
# print GIF pictures
#===============================================================================

print_gif()
{
	cat ${APS_HEADER} - | giftopnm | eval $PNMTOPS | eval $PRINT_PS 
}

#===============================================================================
# print sun rasterfile 
#===============================================================================

print_sunraster()
{
	cat ${APS_HEADER} - | ras2ps $RAS2PS_OPTS | $PRINT_PS 
}

print_sunraster2()
{
	cat ${APS_HEADER} - | rasttopnm | eval $PNMTOPS | eval $PRINT_PS 
}

#===============================================================================
# print postscript
#===============================================================================

print_ps()
{
	cat ${APS_HEADER} - | eval $PRINT_PS
}

#===============================================================================
# print dvi files using dvips->gs
#===============================================================================

#-----------------------------------------------------------
# suported env. variables for print_dvi
#-----------------------------------------------------------
# TEXINPUTS =	list of directories, where pictures reside,
#		that might be included into the printout
# PRINT_DVI =	full command to print dvi files...

print_dvi()
{
	#-----------------------------------------------------------
	# Check wether this site has a working MakeTeXPK installed
	# with the right permissions and similar stuff.
	#-----------------------------------------------------------
	
	if [ "$HAVE_MAKETEXPK" != "True" ] ; then
		DVIPS_OPTS="$DVIPS_OPTS -M"
	fi

	#-----------------------------------------------------------
	# Does the user have a better dvi print program ?
	# Ok, here we go !!
	#-----------------------------------------------------------

	if [ -z "$PRINT_DVI" ]; then

		TEXINPUTS=$TEXINPUTS:${APS_BASEDIR}/test:/tmp:/var/tmp
		export TEXINPUTS

		TMP_FILE=/tmp/aps.$$
		cat ${APS_HEADER} - > $TMP_FILE
		dvips -f $DVIPS_OPTS < $TMP_FILE | eval $PRINT_PS 
	else
		# this user only trusts his dvi2xxx program ;-)
		# hope he knows how to get his data from stdin ;-)
		cat ${APS_HEADER} - | $PRINT_DVI
	fi

	if [ "$TMP_FILE" ]; then
                rm -f $TMP_FILE
        fi
}

#===============================================================================
#
# print raw ascii (perhaps you need a _fast_ listing, eh ;-)
#
#===============================================================================

print_raw()
{
	case $PRINTER in
		*desk*|*djet*|laserjet|ljet*)
			#Translate LF to CR+LF and FF to CR+FF
			printf "\033&k2G"
                        # Perforation Skip Mode off (DIN A4: 66 lines/page)
                        printf "\033&l0L" ;;
	esac

	if [ $PRINT_RAW_SETUP_PRINTER ]; then
		printf $PRINT_RAW_SETUP_PRINTER
	fi

	cat -

	# usually we do a nice formfeed
	if [ -z "$PRINT_RAW_SUPPRESS_FORMFEED" ]; then
		printf "\014"
	fi
}

#===============================================================================
#
# print ascii using a2ps
#
#===============================================================================

print_ascii()
{

	# get job, user and host ...
	# ljo@ljo-slip.DIALIN.CWRU.Edu (L Jonas Olsson)

	LOCK=`dirname ${ACCTFILE}`/lock
	CF=`tail -1 ${LOCK}`
	JOB=`egrep '^J' ${CF} | tail +2c`
	USER=`egrep '^P' ${CF} | tail +2c`
	HOST=`egrep '^H' ${CF} | tail +2c`

	case $PRINTER in
		cdesk*|cdj*|desk*|djet*)	A2PS_MARGIN=1.6
						;;
		*)				# default 1.4"
						A2PS_MARGIN=1.4
						;;
	esac
	
	# For a detailed description of the a2ps commandline options
	# please look up the manpage

	if [ "$JOB" = "stdin" ]; then JOB=""; fi

	A2PS_BASIC_OPTIONS="-X$PAPERSIZE -M$A2PS_MARGIN \
			    -H$JOB -Q$USER -Z$HOST"

	A2PS_STD_OPTIONS="-8 -m -r -ns -nu -nP"

	# FEATURE: see users apsfilterrc or /etc/apsfilterrc
	case $FEATURE in
		1)	A2PS_FEATURES="-p -1 -F9.0"		;;
		2)	A2PS_FEATURES="-F6.9"			;;
		1n)	A2PS_FEATURES="-p -1 -F9.0 -nH -nL"	;;
		2n)	A2PS_FEATURES="-F6.9 -nH -nL"		;;
		1l)	A2PS_FEATURES="-l -1 -F9.0"		;;
		1ln)	A2PS_FEATURES="-l -1 -nH -nL -F9.0"	;;
		*)	A2PS_FEATURES="-F6.9 -nH"		;;
	esac

	# if no user defined options then take the one we provide
	# if user defined A2PS_OPTS, we have to keep the A2PS_BASIC_OPTIONS !!!

	if [ -z "$A2PS_OPTS" ]; then
		# not user defined
		A2PS_OPTS="${A2PS_BASIC_OPTIONS} \
			   ${A2PS_STD_OPTIONS} \
			   ${A2PS_FEATURES}"
	else
		# user defined, but keep BASIC options
		A2PS_OPTS="${A2PS_BASIC_OPTIONS} \
			   ${A2PS_OPTS}"
	fi

	case $PRINTER in
	    djet*|pj*)
		if [ -z "$GS_FEATURES" ]; then
		    # sane defaults for color printer
		    # print ascii texts black&white
		    GS_FEATURES="-dBitsPerPixel=1"
		fi ;;
	esac

	cat ${APS_HEADER} - | a2ps ${A2PS_OPTS} | eval $PRINT_PS
}

#===============================================================================
#
# print data files and fine tune printer settings ...
#
#===============================================================================

print_data()
{
	cat ${APS_HEADER} -
}

#===============================================================================
#
# print HTML files
#
#===============================================================================

print_html()
{
	cat ${APS_HEADER} - | html2ps $HTML2PS_OPTS | $PRINT_PS 
}

#===============================================================================
#
# print PDF files (please note, we need temp files here, see gs docu)
#
#===============================================================================

print_pdf()
{
	cat ${APS_HEADER} - > /tmp/apsfilter.$$.pdf
	pdf2ps /tmp/apsfilter.$$.pdf /tmp/apsfilter.$$.ps
	cat /tmp/apsfilter.$$.ps | eval $PRINT_PS
	rm -f /tmp/apsfilter.$$.pdf /tmp/apsfilter.$$.ps
}

#===============================================================================
#
# print according to file type
#
#===============================================================================

print_auto()
{
	if [ "$COLOR" = "mono" ]; then
		if [ "$HAVE_PNMTOPS" = "True" \
		   -a "$HAVE_PPMTOPGM" = "True" ]; then		
			HAVE_PNMTOPS=True
		else
			HAVE_PNMTOPS=False
		fi
	fi

	case `echo $FILE_TYPE | tr 'A-Z' 'a-z'` in

		*pdf*)
			print_pdf
			;;
		*fig*)
			if [ "$HAVE_FIG2DEV" = "True" ]; then
				print_fig
			else
				fault_filetype
			fi
			;;

		*tiff*)
			if [ "$HAVE_TIFFTOPNM" = "True" \
			  -a "$HAVE_PNMTOPS"  = "True" ]; then
				print_tiff
			else
				fault_filetype
			fi
			;;

		*gif*)
			if [ "$HAVE_GIFTOPNM" = "True" \
			  -a "$HAVE_PNMTOPS"  = "True" ]; then
				print_gif
			else
				fault_filetype
			fi
			;;

		*jpeg*)
			if [ "$HAVE_DJPEG" = "True" \
			  -a "$HAVE_PNMTOPS"  = "True" ]; then
				print_jpeg
			else
				fault_filetype
			fi
			;;

		*pnm*|*pbm*|*ppm*)
			if [ "$HAVE_PNMTOPS" = "True" ]; then
				print_pnm
			else
				fault_filetype
			fi
			;;

		*rasterfile*)
			if [ "$HAVE_RAS2PS" = "True" ]; then
				print_sunraster
			elif [ "$HAVE_RASTTOPNM" = "True" ];then
				print_sunraster2
			else
				fault_filetype
			fi ;;
					
		postscript*)	# we checked presence of gs already...
			print_ps
			;;

		*dvi*)
			if [ "$HAVE_DVIPS" = "True"   \
			   -o -z "$PRINT_DVI" ]; then
				print_dvi
			else
				fault_filetype
			fi ;;

		*data*|*escape*)
			# that's certainly not critical,
			# you're on your own ;-)
			print_data ;;

		*html*)
			if [ "$HAVE_HTML2PS" = "True" ]; then
				print_html
			else
				fault_filetype
			fi ;;

		*ascii*|*text*|*english*|*script*)
			# we checked presence of gs already...
			if [ "$HAVE_A2PS" = "True" ]; then
				print_ascii
			else
				fault_filetype
			fi ;;

 		*)		
			# data we - I'm so sorry - don't know
			fault_filetype ;;
	esac
}

#===============================================================================
#
# UNKNOWN file or method type, too bad ;->
#
#===============================================================================

fault_filetype()
{
    # make noise on system console
    echo "apsfilter: unsupported filetype 
\
	$FILE_TYPE from $LOGINNAME
\
	or missing filter ! 
\
	or perhaps you have to type lpr -Pascii to print an ascii 
\
	file containing control characters or lpr -Praw to print 
\
	a file in your printers native language, when printing data 
\
	files (pcl3, pcl5, ...) ?! " \
    > /dev/console

    # mail to printer admin
    echo "apsfilter: unsupported filetype 
\
	$FILE_TYPE from $LOGINNAME
\
	or missing filter ! 
\
	or perhaps you have to type lpr -Pascii to print an ascii 
\
	file containing control characters or lpr -Praw to print 
\
	a file in your printers native language, when printing data 
\
	files (pcl3, pcl5, ...) ?! " \
    | $MAILX -s "apsfilter: printer fault" $NOTIFY \
    2> /dev/null
}

fault_method()
{
	# make noise on system console
	echo "apsfilter: unknown print method $METHOD" > /dev/console

	# mail to printer admin
	echo "apsfilter: unknown print method $METHOD" \
	| $MAILX -s "apsfilter: printer fault" $NOTIFY \
	2> /dev/null
}

fault_unpacker()
{
	# make noise on system console
	echo "apsfilter: missing $UNPACKER utility to print file" > /dev/console

	# mail to printer admin
	echo "apsfilter: missing $UNPACKER utility to print file" \
	| $MAILX -s "apsfilter: printer fault" $NOTIFY \
	2> /dev/null
}

#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
# / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
#
#   M A I N  ( )
#
#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
# / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
#  / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / /


if [ $METHOD = raw ]; then

	print_raw

else

	if [ -f $FILTERS_FOUND ]; then
	    . $FILTERS_FOUND
	fi

	# Use the file command to figure out what kind of file this is.
	# We cannot just call file on stdin because later we need the
	# whole file for printing. We could copy stdin to disk but this
	# might waste a lot of disk space for large files. Instead we
	# try to copy just enough for file to do its job, later we
	# cat this file header and the remaining stdin together again.
	# The file command may read up to 8k bytes, need to figure out
	# how to copy this much of stdin into a temporary file, try to
	# use head if possible, fallback is to copy the whole file using
	# cat.

	BYTES_NEEDED=8192

	APS_HEADER=/tmp/aps_header.$$

	if head -c -n 1 </dev/null >/dev/null 2>&1; then
		head -c -n $BYTES_NEEDED > ${APS_HEADER}
	elif head -c 1 </dev/null >/dev/null 2>&1; then
		head -c $BYTES_NEEDED > ${APS_HEADER}
	else
		cat - > ${APS_HEADER}
	fi

	set -- `file ${APS_HEADER}`
	shift
	FILE_TYPE=$*

	# if the file was compressed we simply decompress it and call
	# apsfilter again with the resulting uncompressed stream

        case `echo $FILE_TYPE | tr 'A-Z' 'a-z'` in

		*bzip*)
			if [ "$HAVE_BUNZIP2" = "True" ]; then
				cat ${APS_HEADER} - | bunzip2 | ${APS_CMD}
			else
				UNPACKER="bunzip2"
				fault_unpacker
			fi
			;;

		*gzip*)
			if [ "$HAVE_GZIP" = "True" ]; then
				cat ${APS_HEADER} - | gzip -dc | ${APS_CMD}
			else
				UNPACKER=gzip; fault_unpacker
			fi
			;;

		*compress*)
			if [ "$HAVE_COMPRESS" = "True" \
			    -o "$HAVE_GZIP" = "True" ]; then
				cat ${APS_HEADER} - | zcat | ${APS_CMD}
			else
				UNPACKER="compress or gzip"
				fault_unpacker
			fi
			;;

		*frozen*)
			if [ "$HAVE_MELT" = "True" ]; then
				cat ${APS_HEADER} - | fcat | ${APS_CMD}
			else
				UNPACKER=melt; fault_unpacker
			fi
			;;

		*packed*)
			if [ "$HAVE_GZIP" = "True" ]; then
				cat ${APS_HEADER} - | zcat | ${APS_CMD}
			else
				UNPACKER=gzip; fault_unpacker
			fi
			;;

		*)	# it's not compressed

			case $METHOD in

				ascii)	
					print_ascii
					;;
				auto)
					print_auto
					;;
				*)
					fault_method 
					;;
			esac
			;;
	esac

	rm ${APS_HEADER}
fi
