#!/bin/sh
#--------------------------------------------------------------------
#
#--------------------------------------------------------------------
#
#       File:   print_model
#
#       Description:
#
#               Standard printer interface program.
#
#--------------------------------------------------------------------
#
#
# Set debugging,
#
#       DEBUG=0         Turn debugging OFF
#       DEBUG=1         Turn debugging ON
#

#-- Set System Type Variables
systype=`uname -a | (read p1 p2 p3 p4 p5 p6 p7 p8 p9; echo $p1)`
systype2=`uname -a | (read p1 p2 p3 p4 p5 p6 p7 p8 p9; echo $p1 $p3)`

DEBUG=0
APPLICATION_DIR="/usr/genprint"
PRODUCT="genprint"
SYS_SPOOL_DIR="/var/spool"
UNIX_PRT_DIR=${SYS_SPOOL_DIR}/printer/unix_prt_drivers
FORMAT_PROGRAM="process_printjob"
BUILD_TRANSPORT_CMD="process_printcmd"

# --------------------------------------------------------------------
#
#
# Until we get to the point below where the printer port
# and physical printer are initialized, we can't do much
# except exit if the Spooler/Scheduler cancels us.
#
# --------------------------------------------------------------------

trap 'exit' 15

# --------------------------------------------------------------------
#
# We can be clever about getting a hangup or interrupt, though, at least
# until the filter runs. Do this early, even though $LPTELL
# isn't defined, so that we're covered.
#
# --------------------------------------------------------------------

catch_hangup () {
	if [ -n "${LPTELL}" ]
	then
		echo \
"The connection to the printer dropped; perhaps the printer went off-line?" \
		| ${LPTELL} ${printer}
	fi
	return 0
}
catch_interrupt () {
	if [ -n "${LPTELL}" ]
	then
		echo \
"Received an interrupt from the printer.  The reason is unknown,
although a common cause is that the baud rate is too high." \
		| ${LPTELL} ${printer}
	fi
	return 0
}
trap 'catch_hangup; exit_code=129 exit 129' 1
trap 'catch_interrupt; exit_code=129 exit 129' 2 3

# --------------------------------------------------------------------
#
# Most of the time we don't want the standard error to be captured
# by the Spooler, mainly to avoid "Terminated" messages that the
# shell puts out when we get a SIGTERM. We'll save the standard
# error channel under another number, so we can use it when it
# should be captured.
#
# Open another channel to the printer port, for use when the
# regular standard output won't be directed there, such as in
# command substitution (`cmd`).
#
# --------------------------------------------------------------------

if [ "${DEBUG}" = "1" ] 
then
	DEBUG_LOG="/tmp/`basename $0`_debug.log"
	FORMATTER_JOB_DEBUG_LOG="/tmp/`basename $0`_job_debug.log"
        FORMATTER_BANNER_DEBUG_LOG="/tmp/`basename $0`_banner_debug.log"
        TRANSPORT_DEBUG_LOG="/tmp/`basename $0`_transport_debug.log"
	echo "" > ${DEBUG_LOG}
	echo "" >> ${DEBUG_LOG}
	echo "---------------------------------------------------------------------------" >> ${DEBUG_LOG}
	echo "	Date               : `date` " >> ${DEBUG_LOG}
 	echo "	Interface filename : $0 " >> ${DEBUG_LOG}
	echo "	Debug log filename : ${DEBUG_LOG}" >> ${DEBUG_LOG} 
	echo "---------------------------------------------------------------------------" >> ${DEBUG_LOG}
 	echo "Formatter Log = ${FORMATTER_JOB_DEBUG_LOG}" >> ${DEBUG_LOG}
        echo "Formatter Banner Log = ${FORMATTER_BANNER_DEBUG_LOG}" >> ${DEBUG_LOG}
        echo "Transport Log = ${TRANSPORT_DEBUG_LOG}" >> ${DEBUG_LOG}
	echo "---------------------------------------------------------------------------" >> ${DEBUG_LOG}
	echo "" >> ${DEBUG_LOG}
fi
# exec 5>&2 2>/dev/null 3>&1

# ---------------------------------------------------------
#
# Set some globally used variables and functions.
#
# ---------------------------------------------------------

: ${TMPDIR:=/tmp}
: ${SPOOLDIR:=/usr/spool/lp}
: ${TERMINFO:=/usr/lib/terminfo}
: ${CHARSETDIR:=/usr/lib/charsets}

: ${LOCALPATH:=${SPOOLDIR}/bin}
PATH="/bin:/usr/bin:${LOCALPATH}"
CR="\015"
FF="\014"
NL="\012"

asian_sysfont_2_prtfont()
{
    if [ "$systype" = "SunOS" ];  then 

	if		[ -x "/usr/bin/nawk" ];then  
			AWK_CMD="/usr/bin/nawk" 
	elif		[ -x "/bin/awk" ];then  
			AWK_CMD="/bin/awk" 
	elif	[ -x "/usr/bin/awk" ];then  
			AWK_CMD="/usr/bin/awk" 
	else
			return
	fi
    else
	if		[ -x "/bin/awk" ];then  
			AWK_CMD="/bin/awk" 
	elif	[ -x "/usr/bin/awk" ];then  
			AWK_CMD="/usr/bin/awk" 
	else
			return
	fi
    fi

	${AWK_CMD} '{ if(($0~/Song-Medium-GBK-EUC-H /) || ($0~/Kai-Medium-GBK-EUC-H /) || ($0~/Song-Light-GBK-EUC-H /) || ($0~/FangSong-Light-GBK-EUC-H /) || ($0~/Song-Light-GBK-EUC-H /) || ($0~/MSungGBK-Light-GBK2K-H /) || ($0~/Song-Medium-EUC /) || ($0~/Kai-Medium-EUC /) || ($0~/Ming-Light-B5 /) || ($0~/MSung-Medium-B5-H /) || ($0~/Big5-Kaiti /) || ($0~/Big5-Kaiti-Regular /) || ($0~/ShanHeiSun-Light-B5-H /) || ($0~/Baekmuk-Gulim-KSC-EUC-H /) || ($0~/Ming-Light-H /) || ($0~/Gothic-Medium-EUC /))
		for(i=1; i<=NF; i++)
           {if($i ~ /^\(/) { break; }
            if($i~/^\/Song-Medium-GBK-EUC-H/) {$i="/MSung-Light-GBK-EUC-H"; break;}
            if($i~/^\/Kai-Medium-GBK-EUC-H/) {$i="/MKai-Medium-GBK-EUC-H"; break;}
            if($i~/^\/Song-Light-GBK-EUC-H/) {$i="/MSung-Light-GBK-EUC-H"; break;}
            if($i~/^\/FangSong-Light-GBK-EUC-H/) {$i="/CFangSong-Light-GBK-EUC-H"; break;}
            if($i~/^\/MSungGBK-Light-GBK2K-H/) {$i="/MSung-Light-GBK-EUC-H"; break;}
            if($i~/^\/Song-Medium-EUC/) {$i = "/MSung-Light-GBK-EUC-H"; break;}
            if($i~/^\/Kai-Medium-EUC/) {$i = "/MKai-Medium-GBK-EUC-H"; break;}
            if($i~/^\/Ming-Light-B5/) {$i = "/MingMT-Light-B5pc-H"; break;}
            if($i~/^\/MOESung-Regular-B5-H/) {$i="/MingMT-Light-B5pc-H"; break;}
            if($i~/^\/MSung-Medium-B5-H/) {$i="/MingMT-Light-B5pc-H"; break;}
            if($i~/^\/MSung-Light-B5-H/) {$i="/MingMT-Light-B5pc-H"; break;}
            if($i~/^\/Big5-Kaiti/) {$i="/MKai-Medium-B5pc-H"; break;}
            if($i~/^\/Big5-Kaiti-Regular/) {$i="/MKai-Medium-B5pc-H"; break;}
            if($i~/^\/ShanHeiSun-Light-B5-H/) {$i="/MingMT-Light-B5pc-H"; break;}
            if($i~/^\/Baekmuk-Gulim-KSC-EUC-H/) {$i="/MD_Gulim"; break;}
            if($i~/^\/Ming-Light-H/) {$i="/MingMT-Light-CNS-EUC-H"; break;}
            if($i~/^\/Gothic-Medium-EUC/) {$i="/MD_Gulim"; break;}
		}
		{print $0}}
     '
}


asian_prtfont_2_sysfont()
{
	if		[ -x "/bin/awk" ];then  
			AWK_CMD="/bin/awk" 
	elif	[ -x "/usr/bin/awk" ];then  
			AWK_CMD="/usr/bin/awk" 
	else
			return
	fi

	${AWK_CMD} '{ if(($0~/MingMT-Light-B5pc-H/) || ($0~/MSung-Light-GBK-EUC-H/) || ($0~/HG-MinchoL-90ms-RKSJ-H/) || ($0~/MD_BatangChe/))
		for(i=1; i<=NF; i++)
           {if($i~/MingMT-Light-B5pc-H/) {$i="(ShanHeiSun-Light-B5-H)"; break;}
            if($i~/MSung-Light-GBK-EUC-H/) {$i="(MSungGBK-Light-GBK2K-H)"; break;}
            if($i~/HG-MinchoL-90ms-RKSJ-H/) {$i="(Ryumin-Light-EUC-H)"; break;}
            if($i~/MD_BatangChe/) {$i="(Baekmuk-Gulim-KSC-EUC-H)"; break;}
		}
		{print $0}}
     '
}

dbcs_font_download()
{
	file="${1}"
	get_queue_path ${printer}
	RESOL_PS=`grep "ps_resolution=" ${QUEUE_PATH} 2>&1`
	if [ $? -ne 0 ]; then
        	RESOL_PS=600
	else
		echo ${RESOL_PS} | grep printer_setting >/dev/null 2>&1
		if [ $? -eq 0 ]; then
        		RESOL_PS=600
		else
			RESOL_PS=`echo ${RESOL_PS} | awk -F= '{print $2}' 2>&1`
		fi
  	fi
	PAPERSIZE_PS=`grep "ps_paper_size=" ${QUEUE_PATH} 2>&1 | awk -F= '{print $2}' 2>&1 | tr '[:upper:]' '[:lower:]' 2>&1`

	if [ -z "${file}" ];then
    		/usr/bin/gs -q -dBATCH -sDEVICE=pswrite -r${RESOL_PS}x${RESOL_PS} -sPAPERSIZE=${PAPERSIZE_PS} -dNOPAUSE -sOutputFile=- -
	else
    		/usr/bin/gs -q -dBATCH -sDEVICE=pswrite -r${RESOL_PS}x${RESOL_PS} -sPAPERSIZE=${PAPERSIZE_PS} -dNOPAUSE -sOutputFile=- ${file}
	fi
}
 
# ---------------------------------------------------------
#
# Call the formatter and see if you can print the banner
# page using the -b option if the banner is enable by the
# queue.
#
# ---------------------------------------------------------
 
# ---------------------------------------------------------
# check if queue is in user home directory
# ---------------------------------------------------------

get_queue_path() {
   queue_name=$1
	UNIQ_DIR=`awk -F= ' /gen.unique.user.dir/ { print $2 } ' ${UNIX_PRT_DIR}/.${PRODUCT}/props/gen.properties 2>&1`
	USER_HOME=`${APPLICATION_DIR}/bin/ckuser -H -u ${user}`

   if [ -f "${USER_HOME}/.${PRODUCT}/${UNIQ_DIR}/vir_queues/${queue_name}/.${queue_name}" ]; then
      QUEUE_PATH="${USER_HOME}/.${PRODUCT}/${UNIQ_DIR}/vir_queues/${queue_name}/.${queue_name}"
   else
      QUEUE_PATH="${UNIX_PRT_DIR}/vir_queues/${queue_name}/.${queue_name}"
   fi
}

run_first()
{

	# ---------------------------------------------------------
	#
	# Print very verbose messages to the DEBUG_LOG file
	# to help debug problems if DEBUG=1
	#
	# ---------------------------------------------------------

	if [ "${DEBUG}" = "1" ] 
	then
        	echo "\nGot in RUN FIRST ...." >>${DEBUG_LOG}
		echo "	title = $title " >> ${DEBUG_LOG}
		echo "	printer = $printer " >> ${DEBUG_LOG}
		echo "	host = $host " >> ${DEBUG_LOG}
		echo "	user = $user " >> ${DEBUG_LOG}
		echo "	options = $option_list " >> ${DEBUG_LOG}
		echo "	processlist = $processlist" >> ${DEBUG_LOG}
		echo "	file = $1 " >> ${DEBUG_LOG}

		if [ "${nobanner}" != "yes" ]
		then
			echo "" >> ${DEBUG_LOG}
			echo "Banner page:" >> ${DEBUG_LOG}
			echo "	Printing the banner page as follows :" >> ${DEBUG_LOG}
        		echo "	${APPLICATION_DIR}/bin/${FORMAT_PROGRAM} -b -q ${printer} -f \"$1\" -h ${host} -u ${user} -s "${title}" -p \"${processlist}\" -d2 -t ${FORMATTER_BANNER_DEBUG_LOG}" >> ${DEBUG_LOG}
		else
			echo "" >> ${DEBUG_LOG}
			echo "Banner page:" >> ${DEBUG_LOG}
			echo "	Banner page printing disabled from command line." >> ${DEBUG_LOG}
			echo "" >> ${DEBUG_LOG}
		fi
	fi

	# ---------------------------------------------------------
	#
	# If the command line option "nobanner" is specified DO NOT
	# print the banner page. This way we can override the queue
	# default settings.
	#
	# ---------------------------------------------------------

	if [ "${nobanner}" != "yes" ]
	then

		#-----------------------------------------------------
		# Now format the banner page if enabled by the queue 
		#-----------------------------------------------------
		if [ "${DEBUG}" = "1" ]; then
			DEBUG_ARGS="-d2 -t ${FORMATTER_BANNER_DEBUG_LOG}"
		else
			DEBUG_ARGS=""
		fi

		if [ "${DWN_FONT}" = "yes" ];then
			${APPLICATION_DIR}/bin/${FORMAT_PROGRAM} -b -q ${printer} -f "${1}" -h ${host} -u ${user} -s "${title}" -p "${processlist}" ${DEBUG_ARGS} | asian_prtfont_2_sysfont | dbcs_font_download
		else
			${APPLICATION_DIR}/bin/${FORMAT_PROGRAM} -b -q ${printer} -f "$1" -h ${host} -u ${user} -s "${title}" -p "${processlist}" ${DEBUG_ARGS}
		fi
		exit_code=$?
	fi

	#----------------------------------------------------------
	#	 Make sure the banner program existed correctly
	#
	#	 Currently if the banner page exits with exit code
	#	 of "5", it will cause this interface script to
	#	 return without printing the job.
	#----------------------------------------------------------


	if [ "$exit_code" = "5" ]
        then
		if [ "${DEBUG}" = "1" ] 
                then
                        echo "  Formatter exit code : $exit_code" >> ${DEBUG_LOG}
                	echo "  The banner did print -- The job can not be printed due to ${FORMAT_PROGRAM} exit code = $exit_code" >> ${DEBUG_LOG}

                fi
                return $exit_code
        fi

	if [ "${DEBUG}" = "1" ] 
	then
        	echo "  The banner page printed -- OK" >> ${DEBUG_LOG}
	fi

	#----------------------------------------------------------
	#	If we get here, we are thru with the "bannerTitle" 
	#	now we have to worry about printing.
	#----------------------------------------------------------

	if [ "${DEBUG}" = "1" ] 
        then
		if [ "${nobanner}" != "yes" ]
		then
			echo "	exit code : ${exit_code}" >> ${DEBUG_LOG}
		fi
		echo "" >> ${DEBUG_LOG}
		echo "Print data:" >> ${DEBUG_LOG}
		echo "	Formatting print job as follows: " >> ${DEBUG_LOG}
		echo "	${APPLICATION_DIR}/bin/${FORMAT_PROGRAM} -q ${printer} -f \"$1\" -h ${host} -u ${user} -s "${title}" -p \"${processlist}\" -d2 -t ${FORMATTER_JOB_DEBUG_LOG} " >> ${DEBUG_LOG}
	fi


	#-----------------------------------------------
	#	 Now format the print job
	#-----------------------------------------------

	if [ "${DEBUG}" = "1" ]; then
		DEBUG_ARGS="-d2 -t ${FORMATTER_JOB_DEBUG_LOG}"
	else
		DEBUG_ARGS=""
	fi

	if [ "${DWN_FONT}" = "yes" ];then
  		dbcs_font_download ${1} | ${APPLICATION_DIR}/bin/${FORMAT_PROGRAM} -q ${printer} -h ${host} -u ${user} -s "${title}" -p "${processlist}" ${DEBUG_ARGS}
	elif [ "${MAP_FONT}" = "yes" ];then
		${APPLICATION_DIR}/bin/${FORMAT_PROGRAM} -q ${printer} -f "$1" -h ${host} -u ${user} -s "${title}" -p "${processlist}" ${DEBUG_ARGS} | asian_sysfont_2_prtfont 
	else
		${APPLICATION_DIR}/bin/${FORMAT_PROGRAM} -q ${printer} -f "$1" -h ${host} -u ${user} -s "${title}" -p "${processlist}" ${DEBUG_ARGS}
	fi
	exit_code=$?

	if [ "${DEBUG}" = "1" ] 
        then
		echo "	exit code : ${exit_code}" >> ${DEBUG_LOG}
	fi

	return 0
	}

print_jobs()
{

if [ "${DEBUG}" = "1" ]
then			
	echo "" >> ${DEBUG_LOG}
	echo "Started the function PRINT_JOBS" >> ${DEBUG_LOG}
fi

# ------------------------------------------------------------------
#
# Use ${TMPPREFIX} as the prefix for all temporary files, so
# that cleanup is easy. The prefix may be up to 13 characters
# long, so you only have space for one more character to make
# a file name. If necessary, make a directory using this prefix
# for better management of unique temporary file names.
#
# ------------------------------------------------------------------

TMPPREFIX=${TMPDIR}/`uname -n`$$

# ------------------------------------------------------------------
#
# Before exiting, set ${exit_code} to the value with which to exit.
# Otherwise, the exit from this script will be 0.
#
# ------------------------------------------------------------------

trap 'rm -fr ${TMPPREFIX}*; exit ${exit_code}' 0

# ------------------------------------------------------------------
#
# ${LPTELL} is the name of a program that will send its
# standard input to the Spooler. It is used to forward
# the description of a printer fault to the Spooler,
# which uses it in an alert to the administrator.
#
# ------------------------------------------------------------------

if [ ! -x "${LPTELL:=${LOCALPATH}/lp.tell}" ]
then
	fake_lptell () {
		header="no"
		while read line
		do
			if [ "no" = "${header}" ]
			then
				errmsg ERROR ${E_IP_UNKNOWN} \
		"unknown printer/interface failure" \
		"consult your system administrator;
		reasons for failure (if any) follow:"
				header=yes
			fi
			echo "${line}" >&2
		done
		return 1
	}
	LPTELL=fake_lptell
fi

# ------------------------------------------------------------------
#
# ${DRAIN} is the name of a program that will wait
# long enough for data sent to the printer to print.
#
# ------------------------------------------------------------------

if [ -x "${LOCALPATH}/drain.output" ]
then
	DRAIN="${LOCALPATH}/drain.output 5"	# wait only five seconds
else
	DRAIN=
fi

# ------------------------------------------------------------------
#
# ${LPCAT} is the name of a program to use as a default
# filter. Minimally it should copy its standard input to
# the standard output, but it should also trap printer
# faults. The current LPCAT traps hangups (DCD dropping, SIGHUP),
# interrupts (SIGINT, SIGQUIT), broken pipe (SIGPIPE), and
# excess delays in sending data to the printer, interpreting all
# as printer faults.
#
# ------------------------------------------------------------------

if [ ! -x "${LPCAT:=${LOCALPATH}/lp.cat}" ]
then
	LPCAT="cat"
fi

# ------------------------------------------------------------------
#
# ${LPSET} is the name of a program that will set the
# character pitch, line pitch, page width, page length,
# and character set. It helps to have this in a single
# binary program so that (1) it's faster than calls
# to "tput"; and (2) it can access the new Terminfo
# capabilities for printers (on pre SVR3.2 machines, tput can't).
#
# ------------------------------------------------------------------

if [ ! -x "${LPSET:=${LOCALPATH}/lp.set}" ]
then
	fake_lpset () {
		echo H V W L S >&2
		false
	}
	LPSET=fake_lpset
fi

internal_lpset () {

	# ------------------------------------------------------------------
	#
	# The funny business with the "2>&1 1>&3" is to let us capture
	# the standard ERROR, not the standard OUTPUT as is the usual case
	# with foo=`cmd`. The standard output will go to the printer.
	#
	# ------------------------------------------------------------------

	[ -n "${stty1}" ] && stty ${stty1} 0<&1
	chk=`${LPSET} "$1" "$2" "$3" "$4" "$5" 2>&1 1>&3`
	[ -n "${stty2}" ] && stty ${stty2} 0<&1

	# ------------------------------------------------------------------
	#
	# The standard error of the delivered ${LPSET} program
	# is a string of letters, H, V, W, L, S, which correspond
	# to cpi, lpi, width, length, and character set. A letter
	# is present only if the corresponding attribute could not
	# be set.
	#
	# ------------------------------------------------------------------

	for err in ${chk}
	do
		case ${err} in
		H )
			errmsg WARNING ${E_IP_BADCPI} \
		"can't select the character pitch \"${cpi}\"" \
		"check the valid pitches for the printer,
		or consult your system administrator;
		printing continues"
			;;
		V )
			errmsg WARNING ${E_IP_BADLPI} \
		"can't select the line pitch \"${lpi}\"" \
		"check the valid pitches for the printer,
		or consult your system administrator;
		printing continues"
			;;
		W )
			width=${cols}
			errmsg WARNING ${E_IP_BADWIDTH} \
		"can't select the page width \"${width}\"" \
		"check the valid widths for the printer,
		or consult your system administrator;
		printing continues"
			;;
		L )
			length=${lines}
			errmsg WARNING ${E_IP_BADLENGTH} \
		"can't select the page length \"${length}\"" \
		"check the valid lengths for the printer,
		or consult your system administrator;
		printing continues"
			;;
		S )
			errmsg WARNING ${E_IP_BADCHARSET} \
		"can't select the character set \"${CHARSET}\"" \
		"check the name given in the -S option,
		or consult your system administrator;
		printing continues"
			;;
		esac
	done
}


# ------------------------------------------------------------------
#
# ${TPUT} is "tput" IF it works. We'll disable it if we get an
# ugly error message the first time we use it. See the TERM variable
# later in the script.
#
# NOTE: The check we use to see if "tput" works is to use an OLD
# Terminfo capability, like "lines". If it works with that it may
# still fail with some of the newer capabilities like "init" (SVR3.0)
# or "swidm" (SVR3.2), because the version of "tput" we have on your
# machine is older. Thus, on some of the code where ${TPUT} is used
# you'll see "2>/dev/null" being used to avoid ugly error messages.
#
# ------------------------------------------------------------------

TPUT=tput

# ------------------------------------------------------------------
#
# Error message formatter:
#
# Invoke as
#
#	errmsg severity message-number problem help
#
# where severity is "ERROR" or "WARNING", message-number is
# a unique identifier, problem is a short description of the
# problem, and help is a short suggestion for fixing the problem.
#
# ------------------------------------------------------------------

LP_ERR_LABEL="UX:lp"

E_IP_ARGS=1
E_IP_OPTS=2
COMMENTE_IP_FILTER=3
E_IP_STTY=4
E_IP_UNKNOWN=5
E_IP_BADFILE=6
E_IP_BADCHARSET=7
E_IP_BADCPI=8
E_IP_BADLPI=9
E_IP_BADWIDTH=10
E_IP_BADLENGTH=11
E_IP_ERRORS=12		# (in slow.filter)

errmsg () {
	case $1 in
	ERROR )
		sev="  ERROR";
		;;
	WARNING )
		sev="WARNING";
		;;
	esac
#	tag=`expr "${LP_ERR_LABEL}" : "\(.*\):"``expr "${LP_ERR_LABEL}" : ".*:\(.*\)"`


			# -- HP-UX added change for HPUX 11 because >&5 stops HPUX Queues
			if [ "$systype" = "HP-UX" ];  then
				echo "${LP_ERR_LABEL}: ${sev}: $3
						TO FIX: $4" >/dev/null
			elif [ "$systype" = "AIX" ];  then
	   		echo "${LP_ERR_LABEL}: ${sev}: $3
           		TO FIX: $4" >&2
			else
			   echo "${LP_ERR_LABEL}: ${sev}: $3
     		      TO FIX: $4" >&5
			fi
}


# ------------------------------------------------------------------
#
# 	Check arguments
#
# ------------------------------------------------------------------

parse () {
	echo "`expr \"$1\" : \"^[^=]*=\(.*\)\"`"
}

# ------------------------------------------------------------------
#
# This program is invoked as
#
# queuename request-id user title copies options files...
#
# The first four arguments are simply reprinted on the banner page,
# the fifth (copies) is used to control the number of copies to print,
# the sixth (options) is a blank separated list (in a single argument)
# of user or Spooler supplied options (without the -o prefix),
# and the last arguments are the files to print.
#
# ------------------------------------------------------------------

if [ $# -lt 6 ]
then
	errmsg ERROR ${E_IP_ARGS} \
		"wrong number of arguments to interface program" \
		"consult your system administrator"
	exit 1
fi

# ------------------------------------------------------------------
# 
# Initialize all the variables we need for our banner page and any
# command line options passed to the interface by lpsched using the
# -o option 
#
# ------------------------------------------------------------------

printer="$1"
request_id="$2"
user_name="$3"
#-- Only run basename if $4 is not NULL
if [ ! -z "${4}" ];then
   title=`basename "${4}"`
fi
copies="$5"

# ------------------------------------------------------------------
#
# Some system V machines only pass a blank string in the third
# field the "title", If that is the case use the first field
# that has the request_id of the job for printing on the banner 
# page
#
# ------------------------------------------------------------------

if [ "${title}" = "." ] && [ "$systype" = "UnixWare" ]; then
      #-- Only run basename if $6 is not NULL
      if [ ! -z "${6}" ];then
         title=`basename $6`
      fi
fi

if [ "${title}" = "." ] && [ "$systype" = "UNIX_SV" ]; then
      #-- Only run basename if $7 is not NULL
      if [ ! -z "${7}" ];then
         title=`basename $7`
      fi
fi

if [ "${title}" = "" ]  || [ "${title}" = "." ] && [ "$systype" != "HP-UX" ];  then
   title=${request_id}
   if [ "${DEBUG}" = "1" ]; then
      echo "\nThe title string is BLANK -- Will use the request_id instead" >> ${DEBUG_LOG}
      echo "The new title string is     -- $request_id" >> ${DEBUG_LOG}
   fi
fi

# ------------------------------------------------------------------
#
# The nobanner option is a special case, therefore, we have to
# process it separately. We are going to convert the nobanner
# option to something we understand inside the formatter, i.e.
# banner_page=no.  This way we don't break the normal way of
# all the other options
#
# ------------------------------------------------------------------


option_list=`echo "$6" | sed -e "s/nobanner/banner_page\=no/" | sed -e "s/banner_page\=no_page/banner_page\=no/"`

shift 6
files="$*"

#-- This is for a nice title for Our Fax and Hold & Print
#-- HPUX handles the title differently.  If you print from
#-- a command line, the title is set.  If you print from an
#-- app or CDE, the title is not set.

if [ "${title}" = "" ] && [ "$systype" = "HP-UX" ]; then
   titlehold=`echo ${files} |  awk '{print $1}' | sed -e 's/dA/cA/'`
   titlehold1=`cat $titlehold | grep T`
   echo $titlehold1 | grep -q -e '^T *$'
   if [ "$?" = "0" ];then
      # Title is blank... Use the Job ID instead
      titlehold1=`cat $titlehold | grep J`
      title=`basename "${titlehold1}" | sed -e 's/^J//'`
   else
      titlehold=`cat $titlehold | grep T`
      title=`basename "${titlehold1}" | sed -e 's/^T//'`
   fi

   #-- if all else fails, use the spool name
   if [ "$title" = "" ]; then
      title="`echo ${files} |  awk '{print $1}'`"
   fi
fi

user=`echo ${user_name}|sed -e 's/\(.*\)!\(.*\)/\2/' -e 's/@.*//'`

if [ `echo "$2" | grep \!` ] ; then
	host=`echo ${user_name}|sed -e 's/\(.*\)!\(.*\)/\1/'`
else
   if [ `echo "$2" | grep \@` ] ; then
	host=`echo ${user_name}|sed -e 's/\(.*\)@\(.*\)/\2/'`
   else
	host=`uname -n`
   fi
fi


nofilebreak="no"
stty=

inlist=
processlist=""
rotate=no
for i in ${option_list}
do
	case "${inlist}${i}" in

            nobanner | nb ) nobanner="yes"
                            ;;

   banner | yb | banner_page ) nobanner="no"
                            processlist="${processlist}banner_page=yes "
                            ;;

                  n[1-9]* ) processlist="${processlist}no_of_copies=`echo ${i} | sed 's/^n//'` "
                            ;;
	
             gray | black ) processlist="${processlist}print_mode=black "
                            ;;

                    color ) processlist="${processlist}print_mode=color "
                            ;;

	        lpi[1-9]* ) processlist="${processlist}lines_per_inch=`echo ${i} | sed 's/^lpi//'` "
                            ;;

                 tl[0-9]* ) processlist="${processlist}lines_per_page=`echo ${i} | sed 's/^tl//'` "
                            ;;

               ln66| pl66 ) processlist="${processlist}pl66=on " 
                            ;;

                 tm[0-9]* ) processlist="${processlist}top_margin=`echo ${i} | sed 's/^tm//'` " 
                            ;;

                 rm[1-9]* ) processlist="${processlist}page_width=`echo ${i} | sed 's/^rm//'` " 
                            ;;

                 lm[0-9]* ) processlist="${processlist}indentation=`echo ${i} | sed 's/^lm//'` " 
                            ;;

                  eolwrap ) processlist="${processlist}text_wrap=on "
                            ;;

      #-- 3UP, 6UP, 9UP, 12UP, 16UP                            
      [23469][uU][pP] | 1[26][uU][pP]) 
                            processlist="${processlist}multipage_print=`echo ${i} | sed 's/[uU][pP]//'`UP " 
                            ;;

                     half ) processlist="${processlist}multipage_print=2UP " 
                            ;;

                  quarter ) processlist="${processlist}multipage_print=4UP " 
                            ;;

      letter | legal | A3 | A4 | A5 )
                            processlist="${processlist}paper_size=${inlist}${i} "
                            ;;
		
         exec | executive ) processlist="${processlist}paper_size=executive "
                           ;;

             B5-JIS | B5 ) processlist="${processlist}paper_size=B5 "
                           ;;

       11[xX]17 | ledger ) processlist="${processlist}paper_size=ledger "
                           ;;

  com10 | com10env | com10_env ) 
                           processlist="${processlist}paper_size=com10_env "
                           ;;

  com9 | com9env | com9_env ) 
                           processlist="${processlist}paper_size=com9_env "
                           ;;

     DL | DLenv | DL_env ) processlist="${processlist}paper_size=DL_env "		
                           ;;

     C5 | C5env | C5_env ) processlist="${processlist}paper_size=C5_env "	
                           ;;

         B5env  | B5_env ) processlist="${processlist}paper_size=B5_env "
                           ;;

    monarc | monarch_env ) processlist="${processlist}paper_size=monarch_env "	
                           ;;

    landscape | portrait | rlandscape | rportrait ) 
                           orientation="${i}"
                           ;;

                  rotate ) rotate=yes
                           ;;

             10 | 12 | c ) 
                           if [ "${i}" = "c" ];then
                              processlist="${processlist}pitch=16.67 "
                           else
                              processlist="${processlist}pitch=${inlist}${i} "
                           fi
			   ;;

                 simplex ) processlist="${processlist}duplex=none "
                           ;;

   vd | duplex | double | d ) 
                           processlist="${processlist}duplex=long_edge "
                           ;;

             hd | hduplex) processlist="${processlist}duplex=short_edge "
                           ;;

            manual | man ) processlist="${processlist}paper_tray=manual_paper " 
                           ;;

               tray[1-5] ) processlist="${processlist}paper_tray=${i} " 
                           ;;

                    bin0 ) processlist="${processlist}output_bin=standard_bin "
                           ;;

        bin[1-9] | bin10 ) processlist="${processlist}output_bin=${i} "
                           ;;
	
                  staple ) processlist="${processlist}staple=on "
                           ;;
 		
		
	# ---------------------------------------------------------
	# 
	#  Currently unused options.
	#
	# ---------------------------------------------------------

        #raw      ) raw="yes " ;;

        #simple   ) simple="yes" ;;

        #pitch=*  ) pitch=`parse ${i}` ;;
 
        #length=* ) page_length=`parse ${i}` ;;
 
        #indent=* ) indent=`parse ${i}` ;;
 
        #width=*  ) page_width=`parse ${i}` ;;

        #btray=*  ) banner_tray=`parse ${i}` ;;
 
        #bpapersize=* ) banner_paper_size=`parse ${i}` ;;

        #wraptext ) wrap_text="on" ;;

	#upper | lower | manual | manual_envelope | envelope | feeder )
   #                tray="${inlist}${i}" ;;
 
   #     nofilebreak ) nofilebreak="yes" ;;
 
	# ---------------------------------------------------------
	#
	# If you want to add simple-value options (e.g. -o value=a)
	# identify them here.
	#
	# ---------------------------------------------------------
#	value=* )
#		value=`parse ${i}`
#		;;


	# ---------------------------------------------------------
	#
	# If you want to add options that, like "stty",
	# take a list (e.g. -o lopt='a b c'), identify
	# them here and below (look for LOPT).
	#
	# ---------------------------------------------------------
	stty=* | flist=* | lpd=* )
# LOPT	stty=* | flist=* | lpd=* | lopt=* )

		inlist=`expr "${inlist}${i}" : "^\([^=]*=\)"`
		case "${i}" in
		${inlist}\'*\' )
			item=`expr "${i}" : "^[^=]*='*\(.*\)'\$"`
			;;
		${inlist}\' )
			continue
			;;
		${inlist}\'* )
			item=`expr "${i}" : "^[^=]*='*\(.*\)\$"`
			;;
		${inlist}* )
			item=`expr "${i}" : "^[^=]*=\(.*\)\$"`
			;;
		*\' )
			item=`expr "${i}" : "^\(.*\)'\$"`
			;;
		* )
			item="${i}"
			;;
		esac

		#---------------------------------------------------------
		#
		# We don't dare use "eval" because a clever user could
		# put something in an option value that we'd end up
		# exec'ing.
		#
		#---------------------------------------------------------

		case "${inlist}" in
		stty= )
			stty="${stty} ${item}"
			;;
		flist= )
			flist="${flist} ${item}"
			;;
		lpd= )
			lpd="${lpd} ${item}"
			;;
# LOPT		lopt= )
# LOPT			lopt="${lopt} ${item}"
# LOPT			;;
		esac

		case "${i}" in
		${inlist}\'*\' )
			inlist=
			;;
		${inlist}\'* )
			;;
		*\' | ${inlist}* )
			inlist=
			;;
		esac
		;;

	*=* )
		echo ${i} | grep "=" >>/dev/null 2>&1
		if [ $? = 0 ];then
			processlist="${processlist}${i} "
		fi
		;;

	* )
		errmsg WARNING ${E_IP_OPTS} \
			"unrecognized \"-o ${i}\" option" \
			"check the option, resubmit if necessary
		printing continues"
		;;
	esac
done

if [ ! -z "${orientation}" ];then
   if  [ "${rotate}" = "yes" ] && [ "${orientation}" = "landscape" -o "${orientation}" = "portrait" ];then
        orientation="r${orientation}"
   fi
   case ${orientation} in
         rportrait) orientation="rev_portrait" ;;
        rlandscape) orientation="rev_landscape" ;;
   esac
   processlist="${processlist}orientation=${orientation} "  
fi

#---------------------------------------------------------
#
# Additional ``parameters'' are passed via Shell environment
# variables:
#
#	TERM	The printer type (used for Terminfo access)
#	CHARSET	The character set to choose
#	FILTER	The filter to run
#
#---------------------------------------------------------

#---------------------------------------------------------
#
# Set defaults for unset variables.
#
#---------------------------------------------------------

: ${TERM:=unknown}
tput lines 1>/dev/null 2>&1 || TPUT=:

: ${CHARSET:=cs0}

FILTER="/bin/cat"


# ---------------------------------------------------------------
#
# The protocol between the interface program and the Spooler
# is fairly simple:
#
#	All standard error output is assumed to indicate a
#	fault WITH THE REQUEST. The output is mailed to the
#	user who submitted the print request and the print
#	request is finished.
#
#	If the interface program sets a zero exit code,
#	it is assumed that the file printed correctly.
#	If the interface program sets a non-zero exit code
#	less than 128, it is assumed that the file did not
#	print correctly, and the user will be notified.
#	In either case the print request is finished.
#
#	If the interface program sets an exit code greater
#	than 128, it is assumed that the file did not print
#	because of a printer fault. If an alert isn't already
#	active (see below) one will be activated. (Exit code
#	128 should not be used at all. The shell, which executes
#	this program, turns SIGTERM, used to kill this program
#	for a cancellation or disabling, into exit 128. The
#	Spooler thus interprets 128 as SIGTERM.)
#
#	A message sent to the standard input of the ${LPTELL}
#	program is assumed to describe a fault WITH THE PRINTER.
#	The output is used in an alert (if alerts are defined).
#	If the fault recovery is "wait" or "begin", the printer
#	is disabled (killing the interface program if need be),
#	and the print request is left on the queue.
#	If the fault recovery is "continue", the interface program
#	is allowed to wait for the printer fault to be cleared so
#	it can resume printing.
#
# This interface program relies on filters to detect printer faults.
# In absence of a filter provided by the customer, it uses a simple
# filter (${LPCAT}) to detect the class of faults that cause DCD
# (``carrier'') drop. The protocol between the interface program and
# the filter:
#
#	The filter should exit with zero if printing was
#	successful and non-zero if printing failed because
#	of a printer fault. This interface program turns a
#	non-zero exit of the filter into an "exit 129" from
#	itself, thus telling the Spooler that a printer fault
#	(still) exists.
#
#	The filter should report printer faults via a message
#	to its standard error. This interface program takes all
#	standard error output from the filter and feeds it as
#	standard input to the ${LPTELL} program.
#
#	The filter should wait for a printer fault to clear,
#	and should resume printing when the fault clears.
#	Preferably it should resume at the top of the page
#	that was being printed when the fault occurred.
#	If it waits and finishes printing, it should exit
#	with a 0 exit code. If it can't wait, it should exit
#	with a non-zero exit code.
#
#	The interface program expects that ANY message on the
#	standard error from the filter indicates a printer fault.
#	Therefore, a filter should not put user (input) error
#	messages on the standard error, but on the standard output
#	(where the user can read them when he or she examines
#	the print-out).
#
# ---------------------------------------------------------------

badfileyet=
i=1
while [ $i -le $copies ]
do
	for file in "${files}"
	do
		if [ -r "${file}" ]
		then

			# -----------------------------------------------------
			#
			# Here's where we set up the $LPTELL program to
			# capture fault messages, and...
			#
			# Here's where we print the file.
			#
			# We set up a pipeline to $LPTELL, but play a trick
			# to get the filter's standard ERROR piped instead of
			# its standard OUTPUT: Divert the standard error (#2) to
			# the standard output (#1) IN THE PIPELINE. The shell
			# will have changed #1 to be the pipe, not the
			# printer, so diverting #2 connects it to the pipe.
			# We then change the filter's #1 to a copy of the real
			# standard output (the printer port) made earlier,
			# so that is connected back to the printer again.
			#
			# We do all this inside a parenthesized expression
			# so that we can get the exit code; this is necessary
			# because the exit code of a pipeline is the exit
			# code of the right-most command, which isn't the
			# filter.
			#
			# These two tricks could be avoided by using a named
			# pipe to connect the standard error to $LPTELL. In
			# fact an early prototype of this script did just
			# that; however, the named pipe introduced a timing
			# problem. The processes that open a named pipe hang
			# until both ends of the pipe are opened. Cancelling
			# a request or disabling the printer often killed one
			# of the processes, causing the other process to hang
			# forever waiting for the other end of the pipe to
			# be opened.
			#
			# -----------------------------------------------------

			EXIT_CODE=${TMPPREFIX}e
			trap '' 1	# Let the filter handle a hangup
			trap '' 2 3	# and interrupts


			# -----------------------------------------------------
			# 
			# Setup the transport mechanism by using the transport
			# program which will fetch the correct options from the
			# Device Definition Database for this system
			#
			# Use verbose debugging messages if debug is enabled.
			#
			# -----------------------------------------------------
			
			if [ "${DEBUG}" = "1" ]
        		then

                # The cat in the pipe forces a buffered write

				TRANS="| cat |`${APPLICATION_DIR}/bin/${BUILD_TRANSPORT_CMD}  -q ${printer} -h ${host} -u ${user} -j ${title} -d2 -t ${TRANSPORT_DEBUG_LOG}`"
				echo "\n\nSetting up TRANS and calling run_first ..." >> ${DEBUG_LOG}
				echo "	printer = ${printer}" >> ${DEBUG_LOG}
				echo "	host    = ${host}   " >> ${DEBUG_LOG}
				echo "	user    = ${user}   " >> ${DEBUG_LOG}
				echo "	title   = ${title}" >> ${DEBUG_LOG}
				echo "	options = ${option_list}" >> ${DEBUG_LOG}
				echo "	TRANS   = ${TRANS}" >> ${DEBUG_LOG}
			else
                # The cat in the pipe forces a buffered write

				TRANS="| cat |`${APPLICATION_DIR}/bin/${BUILD_TRANSPORT_CMD} -q ${printer} -h ${host} -u ${user} -j ${title}`"
			fi

         ASIAN_ENABLED="NO"
			grep "enable_asian=yes" ${UNIX_PRT_DIR}/.${PRODUCT}/props/app.properties >/dev/null 2>&1
			if [ "${?}" = "0" ];then
         		ASIAN_ENABLED="YES"
					${APPLICATION_DIR}/bin/sniff "$file"          
					if [ "${?}" = "1" ];then
						FONT_MAPPING_IN_QUEUE="NO"
						# ---------------------------------------------------------
						# To get ps_asian_font value.
						# --------------------------------------------------------
						get_queue_path ${printer} >/dev/null 2>&1

						FM=`grep "ps_asian_font" ${QUEUE_PATH} 2>&1`
						if [ "${?}" = "0" ]; then
							FONT_MAPPING_IN_QUEUE="YES"
							FM=`echo ${FM} | awk -F"=" '{print $2}' 2>&1`
							case "${FM}" in 
								option)
										MAP_FONT="yes"
										DWN_FONT="no"
										;;
								download)
										MAP_FONT="no"
										DWN_FONT="yes"
										;;
								*)
										MAP_FONT=""
										DWN_FONT=""
										;;
							esac
							if [ "${DEBUG}" = "1" ];then
								echo "MAP_FONT = ${MAP_FONT}" >> ${DEBUG_LOG}
								echo "DWN_FONT = ${DWN_FONT}" >> ${DEBUG_LOG}
							fi
						fi
						if [ "${DEBUG}" = "1" ];then
							echo "FONT_MAPPING_IN_QUEUE = ${FONT_MAPPING_IN_QUEUE}" >> ${DEBUG_LOG}
						fi
					fi
			fi
			if [ "${DEBUG}" = "1" ];then
				echo "	ASIAN_ENABLED  = ${ASIAN_ENABLED}" >> ${DEBUG_LOG}
			fi

			eval "run_first \"${file}\" ${TRANS}"


			echo $? >${EXIT_CODE}

			exit_code=`cat ${EXIT_CODE}`

			if [ -n "${exit_code}" -a 0 -ne "${exit_code}" ]
			then
				## trap '' 15  # Avoid dying from disable
				sleep 4	    # Give $LPTELL a chance to tell
				exit_code=129 exit 129
			fi

		else

			# ---------------------------------------------------
			#
			# Don't complain about not being able to read
			# a file on second and subsequent copies, unless
			# we've not complained yet. This removes repeated
			# messages about the same file yet reduces the
			# chance that the user can remove a file and not
			# know that we had trouble finding it.
			#
			# ---------------------------------------------------
			
			if [ "${i}" -le 1 -o -z "${badfileyet}" ]
			then
				errmsg WARNING ${E_IP_BADFILE} \
					"cannot read file \"${file}\"" \
					"see if the file still exists and is readable,
		or consult your system administrator;
		printing continues"
				badfileyet=yes
			fi

		fi

	done
	i=`expr $i + 1`

done

if [ -n "${exit_code}" -a 0 -ne "${exit_code}" ]
then
	exit ${exit_code}
fi

${DRAIN}

}

#--Fix for SCO 5 Systems.  SCO adds a blank space before the option name in $5 
#--Which we need to remove.

if [ "$systype2" = "SCO_SV 3.2" ]; then
   args="\"`basename $0`\" \"$1\" \"$2\" \"`echo $3 | sed -e 's/#.*//'`\" \"$4\" \"`echo $5 | sed -e 's/^ //'`\""  
else
   args="\"`basename $0`\" \"$1\" \"$2\" \"`echo $3 | sed -e 's/#.*//'`\" \"$4\" \"$5\""
fi

shift 5
args="$args $*"

if [ "${DEBUG}" = "1" ]
then
	echo "The interface is called with the following arguments:" >> ${DEBUG_LOG}
	echo "	$args" >> ${DEBUG_LOG}
	echo "" >> ${DEBUG_LOG}
fi

eval "print_jobs $args"
 

if [ $? -ne 0 ] ; then
   exit_code=129
else
   exit_code=0
fi

exit $exit_code
