#!/bin/sh
##
#   $Id: lp.sh,v 1.21 2004/10/18 11:48:37 peterc Exp $
#   Copyright (C) 1998-2004 Tarantella, Inc.
#   This software code contains proprietary information 
#   and should be treated as confidential.
#
#  Component: Print System
#  Author: Patrick Caulfield
#
###############################################################################
#
# This is a Tarantella 'replacement' for lp and lpr on UNIX systems.
# Its purpose is to determine if the print job is destined for
# Tarantella and to add an appropriate header (containing the
# Tarantella username) to the file if so.
#
# A print is destined for Tarantella if all of the following are true:
# - The TTA_USERNAME environment variable is set
# - The printer destination is in /etc/ttaprinter.conf
#------------------------------------------------------------------------------
#
# INSERT-MESSAGE-FILE-HERE (do not remove or change this line!)

StdErr() {
    echo "$*" >&2
    return 0
}

#
# We need to be running a shell with getopts
#
if [ -z "$OPTIND" ]
then
  [ -x /bin/ksh ]     && exec /bin/ksh $0 "$@"
  [ -x /usr/bin/ksh ] && exec /usr/bin/ksh $0 "$@"

  StdErr "${m_lp_nogetopts}"
  exit 3
fi

command=`basename $0`
CONF_FILE="/etc/ttaprinter.conf"
case "$0" in
/*/tta_*.tarantella.com/bin/lp*)
    TTA_CONF_FILE=`expr "$0" : '\(.*\)/bin/lp.*'`/etc/ttaprinter.conf
    [ -r "${TTA_CONF_FILE}" ] && CONF_FILE="${TTA_CONF_FILE}"
    ;;
esac
CONF_FILE_LCASE=${TMPDIR:-/tmp}/ttalp1$$
trap 'rm -f ${CONF_FILE_LCASE}; exit' 1 2 3 15

LANG=C LC_ALL=C export LANG LC_ALL

machinearch ()
{
#!/bin/sh
#  $Id: ixiarch.sh,v 10.38 2005/06/20 19:21:26 peterc Exp $
#  Copyright (C) 1996-2005 Tarantella, Inc.
#  This software code contains proprietary information
#  and should be treated as confidential.
#
#  Print canonical syscode for platform

# There are three valid types of command line:
#
# 1.     visionarch
# 2.     visionarch <available codes>...
# 3.	 visionarch [-c|-o]
#
# 1. The architecture is echoed
# 2. The best architecture from the list is returned
# 3. The -c and -o options return just the system Code or the OS type.

# 0) INITIALIZE VARIABLES

# Some of these are historical, but dont cause any harm
PATH=/bin:/usr/bin:/sbin:/usr/sbin:$XDTHOME/bin:$PMWMHOME/bin:$IXIHOME/bin:$PATH


# 1) Arguments
numcodes=0
for i
do
  case $i in
    -c )
      codeonly=1
    ;;
  
    -o )
      osonly=1
    ;;

    -n )
      if [ -z "$codeonly" -a -z "$osonly" ]
      then
	  displayname=1	
      fi
    ;;
 
    * )
      checkcodes="$checkcodes $i"
      numcodes=`expr $numcodes + 1`
    ;;

   esac
done

# fast exit
if [ $numcodes = 1 ]
then
  echo $checkcodes
  exit 0
fi


# 2) MESSAGES
myname=`basename $0`

#  First define some messages.
#  They get overwritten by sourcing from a file, scripts.ll_TT,
#  so there's no need to translate them here.  

#  Messages for the visionarch script.
#  These follow text like "visionarch: !4! ", and may extend to several lines.
msg_xdtarch_no_uname=\
'No uname command found.'
msg_xdtarch_os_cpu=\
'Cannot recognize the Operating System or processor type.'
msg_xdtarch_ver_rel=\
'Cannot calculate version or release.'
msg_xdtarch_no_match=\
'Cannot find matching installed system.'

#  End of messages
# Try to find a language script
posslangfiles=""
for lang in C $IXILANG $PANLANG $LANG
do
  for pathname in $XDTHOME/bin/scripts. $PMWMHOME/bin/scripts. $IXIHOME/bin/scripts. ./scripts.
  do
    posslangfiles="$posslangfiles $pathname.$lang"
  done
done

# see if we can find one of those language files
for f in $posslangfiles
do
  if [ -f $f ]
  then
    . $scriptslangfile			# source it
    break
  fi						
done
  
# 3) TRY UNAME AND SET UP VARIABLES

unamev=`uname -v 2>/dev/null`
if [ $? -ne 0 ]
then
  # This isn't really a UNIX system is it?
  echo >&2  "$myname: !2! $msg_xdtarch_no_uname"
  exit 2
fi

U_SYSTEM=`uname -s 2>/dev/null`  || U_SYSTEM=UNKNOWN
U_RELEASE=`uname -r 2>/dev/null` || U_RELEASE=UNKNOWN
U_VERSION=`uname -v 2>/dev/null` || U_VERSION=UNKNOWN

# Some machines use -m arg to return 'model' rather
# than architecture.  For example, NCR SVR4 returns
# 3433,3434.  On such machines need to use -p which
# returns processor.

for MACHARG in m p
do
    U_MACHINE=`uname -"$MACHARG" 2>/dev/null` || U_MACHINE=UNKNOWN

    # 4)  FIND THE MACHINE
    # Note that we only look for cpu/os combinations our products currently
    # support - if you want better matching, most GNU software comes with
    # a script called 'config.guess' which does a more thorough job (and
    # has totally different output!)

    CPU= 			# Characters 1-2 of syscode
    OS= 			# Characters 3-4 of syscode
    VER=			# Digits 5-6 of syscode
    REL= 			# Digits 7-8 of syscode


    case ${U_MACHINE}::${U_SYSTEM}::${U_RELEASE}::${U_VERSION} in
      # Intel FreeBSD
      i*::FreeBSD::*:* )
        CPU=i3
        OS=fb
        NAME="FreeBSD (Intel)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # MacOS X
      powerpc::Darwin::*::*)
        CPU=pp
        OS=dw
        NAME="Darwin (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # PowerPC Linux
      ppc*::Linux::*::*)
        CPU=pp
        OS=li
        NAME="Linux (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # Intel Linux
      i*::Linux::*::* )
	CPU=i3
	OS=li
	NAME="Linux (Intel)"
	VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
	REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
      ;;
      # Athlon 64 Linux
      x86_64::Linux::*::* )
	CPU=i3
	OS=li
	NAME="Linux (AMD 64)"
	VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
	REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
      ;;
      # PowerPC Linux
      ppc*::Linux::*::* )
        CPU=pp
        OS=li
        NAME="Linux (PowerPC)"
        VER=`expr $U_RELEASE : '[^0-9]*\([0-9][0-9]*\)[^0-9]'`
        REL=`expr $U_RELEASE : '[^0-9]*[0-9][0-9]*[^0-9]\([0-9][0-9]*\)'`
       ;;
      # Sequent (Intel)
      i*::DYNIX*::*::* )
	CPU=i3
	OS=dy
	NAME="Sequent DYNIX/ptx (Intel)"
	VER=`expr $U_VERSION : 'V\([0-9]\).*'`
	REL=`expr $U_VERSION : 'V[0-9].\([0-9].[0-9]\)' | sed 's/\.//g'`
      ;;

      # The Sun family
      *::SunOS::4.*::* )
	CPU=sp
	OS=su
	VER=4
	NAME="Sun SunOS (Sparc)"
	REL=`expr $U_RELEASE : '4.\([^_]*\)' | sed 's/[^0-9]//g'`
      ;;
      sun*::SunOS::5.*::* )
	CPU=sp
	OS=so
	VER=5
	NAME="Sun Solaris (Sparc)"
	REL=`expr $U_RELEASE : '5.\([0-9][0-9]*\).*' | sed 's/[^0-9]//g'`
      ;;
      *86*::SunOS::5.*::* )
	CPU=i3
	OS=so
	VER=5
	NAME="Sun Solaris (Intel)"
	REL=`expr $U_RELEASE : '5.\(.*\)' | sed 's/[^0-9]//g'`
      ;;
      *::SunOS::5.*::* )
	CPU=sp
	OS=so
	VER=5
	NAME="Sun Solaris (Sparc)"
	REL=`expr $U_RELEASE : '5.\([0-9][0-9]*\).*' | sed 's/[^0-9]//g'`
      ;;

      # HP
      *::HP-UX::*::* )
	CPU=pa
	OS=hp
	NAME="Hewlett-Packard HP-UX (PA-RISC)"
	VER=`expr $U_RELEASE : '[^.]*.\([0-9]*\).*'`
	REL=`expr $U_RELEASE : '[^.]*.[^.]*.\([0-9]*\)'`
      ;;

      # Data General
      *::dgux::5.4*::* )
	CPU=m8
	OS=dg
	VER=54
	NAME="Data General DG/UX (Motorola)"
	REL=`expr $U_RELEASE : '5.4\(.*\)' | sed 's/[^0-9]//g' | sed 's/\(.\).*\(.\)$/\1\2/'`
      ;;

      # Data General on Intel
      *::dgux::R4*::* )
	case `uname -p`  in
	  m* )
	    CPU=m8 ;;
	  * )
	    CPU=i3 ;;
	esac
	OS=dg
	VER=04
	NAME="Data General DG/UX (Intel)"
	REL=`expr $U_RELEASE : 'R4.\(.*\)' | sed 's/[^0-9]//g'`
        REL=`echo $REL | sed 's/\(..\).*/\1/'`
      ;;

      # OSF/1
      alpha::OSF1::*::* )
	CPU=ax
	OS=o1
	NAME="DEC OSF/1 (Alpha)"
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # ULTRIX
      *::ULTRIX::*::* )
	CPU=mp
	OS=ul
	NAME="DEC Ultrix (MIPS)"
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # IRIX
      *::IRIX::4.*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;
      
      *::IRIX::5.1::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*.[^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Note
      # If we ever get minor release numbers of 5.2 we'll have to do
      # something different
      *::IRIX::5.2::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=20
      ;;
      # Note
      # This system does not exist yet
      *::IRIX::5.2.*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # catchall for other irix versions
      # 6.4 and later change from IRIX to IRIX64
      *::IRIX*::*::* )
	CPU=mp
	OS=ir
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # AIX
      # note that we can't figure out the patch level of a 3.2.x (x<4)
      # system (even IBM can't tell you immediately!)
      *::AIX::*::* )
	CPU=rs
	OS=ai
	NAME="IBM AIX (Risc)"
	VER=$U_VERSION
	REL=$U_RELEASE
      ;;

      # RISC OS (the mips variety, not acorn)
      # version 5 like output
      mips::*::*::RISCos )
	CPU=mp
	OS=ro
	VER=`echo $U_RELEASE | sed 's/\([^.]*\).*/\1/' | sed 's/[^0-9]//g'`
	REL=`echo $U_RELEASE | sed 's/[^.]*.\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;
      # version 4 like output
      mips::*::*::UMIPS )
	CPU=mp
	OS=ro
	VER=`echo $U_RELEASE | sed 's/\([0-9]*\).*/\1/'`
	REL=`echo $U_RELEASE | sed 's/[0-9]*\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Siemens Nixdorf mips R4000 (at least)
      R4000::*::*::* )
	CPU=mp
	OS=sx
	NAME="Siemens Nixdorf SINIX (MIPS)"
	VER=`echo $U_RELEASE | sed 's/\([0-9]*\).*/\1/'`
	REL=`echo $U_RELEASE | sed 's/[0-9]*\(.*\)/\1/' | sed 's/[^0-9]//g'`
      ;;

      # Motorola SVR4
      *88*::*::4*::* )
	CPU=m8
	OS=mo
	VER=`expr $U_VERSION : '[^V]*.\([^.]*\).*' | sed 's/[^0-9]//g'`
	REL=`expr $U_VERSION : '[^V]*.[^.]*.\(.*\)' | sed 's/[^0-9]//g'`
      ;;

      # windows nt with nutcracker
      *::Windows_NT::*::* )
	CPU=i3
	OS=wi
	VER="$U_RELEASE"
	REL="$U_VERSION"
      ;;

      DRS*::*::*::* )
	  PROC=`uname -p 2>/dev/null` || PROC=UNKNOWN
	  case "$PROC" in
	    sparc | SPARC )
	      CPU=sp
	      OS=nx
	      NAME="ICL DRS/NX (Sparc)"
	      ;;
	    i386 )
	      CPU=i386
	      OS=nx
	      NAME="ICL DRS/NX (Intel)"
	      ;;
	  esac

	  VER=`expr $U_VERSION : '\([0-9]\).*'`
	  REL=`expr $U_VERSION : '[0-9]..*\([0-9].[0-9]\)' | sed 's/\.//g'`
      ;;

      
      *::UnixWare::*::* )
	CPU=i3
	OS=un
	NAME="SCO UnixWare (Intel)"
	VER=`expr $U_VERSION : '\([0-9]\)'`
	REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
	if [ -z "$REL" ]; then
		REL=00
        elif [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] ; then
		REL="$REL"0
	fi
	;;

      *::OpenUNIX::*::* )
        CPU=i3
        OS=un
        NAME="SCO UnixWare (Intel)"
        VER=`expr $U_VERSION : '\([0-9]\)'`
        REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
        if [ -z "$REL" ]; then
                REL=00
        elif [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] ; then
                REL="$REL"0
        fi
        ;;

      # Various Intel based Unixen.  These seem particularly reluctant
      # to divulge their OS name, so we have to grep through
      # various system files to find the OS string

      *86*::*::*::* )
	if grep -s -i UnixWare /stand/boot 2>/dev/null 1>&2 || strings /stand/1/unix_mp 2>/dev/null | grep -s -i Unixware 2>/dev/null 1>&2
	then
          # It's some version of Unixware obviously
	  CPU=i3
	  OS=un
	  NAME="SCO UnixWare (Intel)"
          if expr $U_VERSION : 'D\([0-9]*.*\)' 2>/dev/null 1>&2
	  then
            # It's a date stamped version ; we dont yet know how to figure out
            # which so just pretend that it is unixware 212
            VER=02
            REL=12
          else
	    VER=`expr $U_VERSION : '\([0-9]\)'`
	    REL=`expr $U_VERSION : '[0-9].\(.*\)' | sed -e 's/\.//'`
	    if [ "x`expr $REL : '[0-9]\([0-9]\)'`" = "x" ] 
	    then
		REL="$REL"0
	    fi
          fi
	else
	  if [ "$U_SYSTEM" = "SCO_SV" ]
	  then
	    CPU=i3
	    OS=sc
	    VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	    NAME="SCO OpenServer (Intel)"
	    # just the release string ie: 3.2v5.0.0
	    relstr=`uname -X | grep Release | awk '{ print $3 }'`
	    # just the major SCO version after the SVR? (3.2v) bit
	    U_VERSION=`expr ${relstr} : '[0-9.]*v\([0-9]\)[0-9.]*'`
	    REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	  else
	    if grep -s 'The Santa Cruz Operation' /etc/gettydefs 2>/dev/null 1>&2
	    then
	      CPU=i3
	      OS=sc
	      NAME="SCO Unix (Intel)"
	      VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	      REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	    else
	      # DYNIX/ptx V2 doesn't return 'DYNIX' or 'ptx' in uname.
	      # This kludge may work, may not, it's either this
	      # or flip a coin!   
	      if grep -s 'ptx' /etc/versionlog 2>/dev/null 1>&2
	      then
		CPU=i3
		OS=dy
		NAME="Sequent DYNIX/ptx (Intel)"
		VER=`expr $U_VERSION : 'V\([0-9]\).*'`
		REL=`expr $U_VERSION : 'V[0-9].\([0-9].[0-9]\)' | sed 's/\.//g'`
	      else
	        # Assume OS must be System V Release 4.
	        CPU=i3
	        OS=sv
		NAME="System V Release 4 (Intel)"
	        VER=`expr $U_RELEASE : '^\([0-9]*\)'`
	        REL=`expr ${U_RELEASE}::${U_VERSION} : '[0-9]*\(.*\)' | sed 's/[^0-9]//g'`
	      fi
	    fi
	  fi
	fi
	;;	
    esac

    if [ -n "$CPU" -a -n "$OS" -a -n "$VER" -a -n "$REL" ]
    then
	break
    fi
done

# 5) Do sanity checking and cleanup
VER=`echo $VER | sed 's/[^0-9]//g'`
REL=`echo $REL | sed 's/[^0-9]//g'`

if [ -z "$CPU" -o -z "$OS" ]
then
  echo "$myname: !10! $msg_xdtarch_os_cpu"
  exit 10
fi

if [ -z "$VER" -o -z "$REL" ]
then
  echo "$myname: !11! $msg_xdtarch_ver_rel"
  exit 11
fi

# Add leading zeroes
REL=`echo 0$REL | sed 's/.*\(..\)/\1/'`
VER=`echo 0$VER | sed 's/.*\(..\)/\1/'`

# 6) So we now know it all

syscode=$CPU$OS$VER$REL

if  test -n "$codeonly"
then
    echo $CPU$OS
    exit 0
fi

if  test -n "$osonly"
then
    echo $VER$REL
    exit 0
fi

# 7) Check for codes given on the command line

if [ ! -z "$checkcodes" ]
then
    for i in $checkcodes
    do
	# Filter the input $checkcodes by matching CPU and OS, and strip
	# them off leaving just the VER and REL.  The tr command replaces
	# spaces by line-feeds, so that the following sort can do its stuff.
	posscodes=`echo $checkcodes | tr ' ' '\012' \
				| sed -ne "s/$CPU$OS//p" | sort -n`
	if [ -z "$posscodes" ]
	then				# None supplied for correct CPU+OS
	    echo >&2 "$myname: !5! $msg_xdtarch_no_match"
	    exit 5
	fi 

	# Some of them are the right platform.
	# The following algorithm returns the greatest possible code which
	# is older than this syscode, or, failing that, the least possible
	# code which is more recent than this one.

	for ver_rel in $posscodes
	do
	    if [ $VER$REL -eq $ver_rel ]
	    then 			# bingo we have this exact release
		echo $syscode
		exit 0
	    elif [ $VER$REL -gt $ver_rel ]
	    then 			# store this previous version
		priorcode=$CPU$OS$ver_rel
	    else 			# $VER$REL is < $ver_rel
		if [ -n "$priorcode" ]
		then
		    echo $priorcode
		    exit 0
		else
		    # Oh dear, we have no previous version so we should use
		    # the oldest newer version which is this current one ...
		    echo $CPU$OS$ver_rel
		    exit 0
		fi
	    fi
	done
    done
    if [ -n "$priorcode" ]
    then
        echo $priorcode
        exit 0
    fi
else
    if [ -n "$displayname" ]
    then
	echo "$NAME"
    else
	echo $syscode
    fi
fi

}
MACHINEARCH=`machinearch`
MACHINEFLAVOR=""
LSBFLAVOR=""
if [  `expr $MACHINEARCH : ..li....` -ne 0 ] ; then
	distrib=`ls /etc/*-release 2>/dev/null`
	n_distrib=`echo $distrib | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]'`
        
        for f_distrib in $n_distrib ; do 
	  case "$f_distrib" in
	    *turbolinux* )
	        MACHINEFLAVOR="turbolinux"
		;;
	    *suse* )
	        MACHINEFLAVOR="suse"
	        ;;
	    *caldera* )
                MACHINEFLAVOR="caldera"
                ;;
	    *redhat*|*fedora* )
	        MACHINEFLAVOR="redhat"
	        ;;
            *lsb* )
                eval `grep ^DISTRIB_ID /etc/lsb-release`
                case "$DISTRIB_ID" in
                 *SuSE* )
                        LSBFLAVOR="suse"
                        ;;
                 "SCO Linux"* ) 
                        LSBFLAVOR="scolinux"
                        ;;
                 *UnitedLinux* ) 
                        LSBFLAVOR="unitedlinux"
                        ;;
                esac
                ;;
	    * )
		# Caldera and Debian don't have a -release.
		# But Debian has a debian_version
		if [ -f /etc/debian_version ] ; then
			MACHINEFLAVOR="debian"
		else
			distrib=`rpm -q -a 2>/dev/null | grep OpenLinux 2>/dev/null`
			r_distrib=`echo $distrib | LANG=C LC_ALL=C tr '[A-Z]' '[a-z]'`
			case "$r_distrib" in
				*openlinux* )
					MACHINEFLAVOR="caldera"
					;;
			esac
		fi
     		;;
	  esac
        done
        # use the LSB flavor iff we haven't determined a flavor from files
        # and packages.
        if [ -z "$MACHINEFLAVOR" -a  ! -z "$LSBFLAVOR" ] ; then
                MACHINEFLAVOR=$LSBFLAVOR
        fi
fi




#
# Get the Tarantella bin directory.  We can't rely on any package information
# because this script may be running on a third tier, so we get the directory
# from the /etc/ttaprinter.conf file, and check that it contains this script.
# $1 to this function is the name (lp or lpr) by which this script was called.
#
GetTTABinDir()
{
    TTABINDIR=`sed -n '/^PATH=/{
s/^PATH=//
s/:.*//
p
q
}' $CONF_FILE 2>/dev/null`
    if [ -n "$TTABINDIR" -a -n "$1" -a -f "$TTABINDIR/$1" ]; then
	echo $TTABINDIR
    else
    	echo /opt/tarantella/bin	# default if it didn't work
    fi
    return 0
}

# Get the name of the printer associated with a Tarantella host name (from
# the information stored in the /etc/ttaprinter.conf configuration file).
#
# Convert environment variables and the content of the config file
# to lower-case, to avoid nonsense like "foo.bar.com" v "foo.bar.COM"
#
# An explicit LPDEST (or PRINTER) setting takes precedence over anything else.
#
GetTTAPrinter()
{
    recursive=""
    case "$1" in
    "") [ -r "${CONF_FILE}" ] || return 1
        tr '[A-Z]' '[a-z]' <${CONF_FILE} >${CONF_FILE_LCASE}
        shift;;
    -recursive) 
	recursive="t"
	shift;;
    *)  echo "$1"
	return 0
    esac
    for name do
	[ -z "${name}" ] && continue
        names=`echo "${name}" | tr '[A-Z]' '[a-z]'`
	case "${names}" in
	*.*) names="${names} `expr \"${names}\" : '\([^\.]*\).*'`" terminator=' |$';;
	*)   terminator=' |\.|$'
	esac
	for DNSname in ${names}; do
	    entries=`egrep -n "tta_host=${DNSname}(${terminator})" <${CONF_FILE_LCASE}`
	    numEntries=0; [ -n "${entries}" ] && numEntries=`echo "${entries}" | wc -l`
	    if [ ${numEntries} -ge 1 ]; then
		linenum=`echo "${entries}" | tail -1 | sed 's/:.*//'`
		sed -n "${linenum}{
s/.*LPDEST=//
s/[; 	].*//
p
q
}" ${CONF_FILE}
		return 0
	    fi
	done
    done
    # Final attempt: try for a local printer if we are a TTA server
    if [ -z "${recursive}" ]; then
	ttaHostName=`GetTTABinDir "$command"`/bin/ttahostname
	if [ -x "${ttaHostName}" ]; then
	    localHostName=`${ttaHostName}`
	    printer=`GetTTAPrinter -recursive "${localHostName}"`
	    [ -n "${printer}" ] && { echo "${printer}"; return 0; }
	fi
    fi
    [ -n "${TTA_PRINT_DEBUG}" ] && StdErr "${m_lp_noprtdef1}${CONF_FILE}${m_lp_noprtdef2}$*"
    return 1
}

#
# Strip the Tarantella bin directory out of the PATH to avoid potential
# problems when calling the real lp{r} commands.  Also strip out "." 
#
# $1 to this function is the name (lp or lpr) by which this script was called.
#
StripPath()
{
    TTABINDIR=`GetTTABinDir "$1"`	# TTABINDIR = (eg) /opt/tarantella/bin
    echo "$PATH" | sed "s|:${TTABINDIR}:|:|g
s|^${TTABINDIR}:||
s|:${TTABINDIR}\$||
s|:\.:|:|g
s|^\.:||
s|:\.\$||
s|:::*|:|g
s|^:||
s|:\$||"
    return 0
}

#
# Use the command-passed title for the job name (if there is one) otherwise 
# use the name of the first file. If that all fails, (ie: the job is from 
# stdin) then invent something.
#
GetTitle()
{
    if [ -n "$1" ]; then
	echo "$1"
    elif [ -n "$2" ]; then
	basename $2
    else
	echo "stdin"
    fi
    return 0
}

#
# Find the "real" lp and lpr commands, and determine whether to use lp or lpr
# to really print.
#
# If available, try to use the same command name that was used to invoke
# this script, thus avoiding possible semantic conflicts (eg lp and lpr
# both support a -s option, but they have completely different meanings).
# 
# If there is no option but to call the "other" command, remove all command
# options before doing do.  This is not ideal, but is better than allowing
# options to be interpreted wrongly.
#
real_command="" real_lpr="" real_lp=""
if [ -f /usr/bin/lp ];  then real_lp="/usr/bin/lp"   ; fi
if [ -f /bin/lp ];      then real_lp="/bin/lp"       ; fi
if [ -f /usr/ucb/lpr ]; then real_lpr="/usr/ucb/lpr" ; fi
if [ -f /usr/bin/lpr ]; then real_lpr="/usr/bin/lpr" ; fi
if [ -f /bin/lpr ];     then real_lpr="/bin/lpr"     ; fi

case "$command" in
lpr) if [ -n "$real_lpr" ]; then
	real_command="$real_lpr"
    elif [ -n "$real_lp" ]; then
	real_command="$real_lp"
    else
	StdErr "${m_lp_nosyslp}"
	exit 2
    fi ;;
lp) if [ -n "$real_lp" ]; then
	real_command="$real_lp"
    elif [ -n "$real_lpr" ]; then
	real_command="$real_lpr"
    else
	StdErr "${m_lp_nosyslp}"
	exit 2
    fi ;;
*)  StdErr "${m_lp_badname}"
    exit 2
esac

# The system lpr command on HP-UX is broken (it's a shell script front end
# to lp, which doesn't do any argument translation).  We therefore break our
# usual rule, and run lp regardless of whether we were called as lp or lpr.
case "$MACHINEARCH" in
pahp*)	[ -n "$real_lp" ] && real_command="$real_lp" ;;
esac

[ -n "$TTA_PRINT_DEBUG" ] && StdErr "${m_lp_realcmd}${real_command}"

#
# Find the 'hostname' command
#
real_hostname=""
if [ -f /bin/hostname ];     then real_hostname="/bin/hostname"     ; fi
if [ -f /usr/bin/hostname ]; then real_hostname="/usr/bin/hostname" ; fi
if [ -f /usr/ucb/hostname ]; then real_hostname="/usr/ucb/hostname" ; fi

#
# Parse the args. Here we just extract the information that is relevant
# to us.
# The arglist here is copied from the Solaris 2.6 manual page so
# it should be fairly complete.
# 
copies=1 title="" args="" options="" TTA_PRINTER=""

if [ "$command" = "lp" ]; then
  # Primary env variable is LPDEST, use PRINTER if not set
  printer=`GetTTAPrinter "${LPDEST:-$PRINTER}" "${TTA_PEERDNSNAME}" "${TTA_EXTDNSNAME}" "${TTA_PRIMARY_DNSNAME}"`
  rm -f ${CONF_FILE_LCASE} >/dev/null 2>&1
  # lp arguments
  while getopts cmpswrd:f:H:n:o:P:q:S:t:T:y: name; do
    case $name in
      d) TTA_PRINTER=$OPTARG ;;
      n) copies=$OPTARG ;;
      t) title=$OPTARG ;;
      o) options="${options} ${OPTARG}" ;;
      cmpswr) args="$args -$name" ;;
      *) args="$args -$name $OPTARG"
    esac
  done
  # strip the leading space from options
  [ -n "${options}" ] && options=`expr "${options}" : '.\(.*\)'`
elif [ "$command" = "lpr" ]; then
  # Primary env variable is PRINTER, use LPDEST if not set
  printer=`GetTTAPrinter "${PRINTER:-$LPDEST}" "${TTA_PEERDNSNAME}" "${TTA_EXTDNSNAME}" "${TTA_PRIMARY_DNSNAME}"`
  rm -f ${CONF_FILE_LCASE} >/dev/null 2>&1
  # lpr arguments
  while getopts cdfghlnmprstvP:\#:1:2:3:4:C:J:T:U:i:w: name; do
    case $name in
      P) TTA_PRINTER=$OPTARG ;;
      \#) copies=$OPTARG ;;
      T) title=$OPTARG ;;
      cdfghlnmprstv) args="$args -$name" ;;
      *) args="$args -$name $OPTARG"
    esac
  done
fi

# If TTA_PRINTER has been specified, check to see if it's the name of a printer
# in /etc/ttaprinter.conf.  If it isn't, assume that it's a client printer name,
# and pass it to the client as a field in the job header.
if [ -n "$TTA_PRINTER" -a -n "`grep \"LPDEST=$TTA_PRINTER \" $CONF_FILE 2>/dev/null`" ]; then
    printer="$TTA_PRINTER"
    TTA_PRINTER=""
fi

[ -n "$TTA_PRINT_DEBUG" ] && StdErr "${m_lp_usingprt}${printer:-<null>} (LPDEST=${LPDEST:-<null>},PRINTER=${PRINTER:-<null>},TTA_PRINTER=${TTA_PRINTER:-<null>})"

#
# Honour TMPDIR if set, and create a temp file for the header information
# If we can't delete an existing TMPFILE then just lp the file.
#
TMPFILE=${TMPDIR:-/tmp}/ttalp$$
NULLS=${TMPDIR:-/tmp}/ttalp0$$
rm -f $NULLS $TMPFILE >/dev/null 2>&1

#
# If the print is not destined for a Tarantella printer or the TTA_USERNAME
# variable is not set than just send the command on its way
#
if [ -z "`grep LPDEST=$printer $CONF_FILE 2>/dev/null`" -o -z "$TTA_USERNAME" -o -z "$printer" -o -f "$TMPFILE" ]
then
  if [ -n "$TTA_PRINT_DEBUG" ]; then
    [ -z "$printer" ] && StdErr "${m_lp_noprtname}"
    [ -z "`grep LPDEST=$printer $CONF_FILE 2>/dev/null`" ] && StdErr "${m_lp_noprtentry1}${printer:-<null>}${m_lp_noprtentry2}${CONF_FILE}"
    [ -z "$TTA_USERNAME" ] && StdErr "${m_lp_nottauser}"
    [ -f $TMPFILE ] && StdErr "${m_lp_cantcreatetmp}${TMPFILE}"
  fi
  if [ -z "$TTA_USERNAME" -o -f "$TMPFILE" ]
  then
    StdErr "${m_lp_cantcreateheader}"
  else
    StdErr "${printer:-<null>}${m_lp_not_ttaprinter}"
  fi
  [ -n "$printer" ] && LPDEST="$printer" PRINTER="$printer" export LPDEST PRINTER
  # Remove Tarantella directory from PATH before calling real lp{r} command
  PATH=`StripPath "$command"` export PATH
  case "$command" in
  *lpr) case "$real_command" in
      *lpr) $real_command "$@" ;;		# lpr->lpr
      *)  shift `expr $OPTIND - 1`		# lpr->lp
	  $real_command -n $copies -t `GetTitle "$title" "$1"` "$@"
      esac ;;
  *) case "$real_command" in
      *lpr) shift `expr $OPTIND - 1`		# lp->lpr
	  $real_command -\#$copies -T`GetTitle "$title" "$1"` "$@" ;;
      *)  $real_command "$@"			# lp->lp
      esac
  esac
  exit $?
fi

#
# Get file names to the front of the arguments list
#
shift `expr $OPTIND - 1`

#
# Create the header -- all this palaver because Unixes are not as
# standard as a lot of people would have you think.
#
if [ -c /dev/zero ]
then
  dd if=/dev/zero bs=1024 count=1 of=$NULLS >/dev/null 2>&1
else
  printf ' '|dd of=$NULLS seek=1024 bs=1 >/dev/null 2>&1
fi

# dd on UnixWare needs conv=notrunc to stop it truncating its output file
# - even if it's standard output with a ">>" redirection.
CONV_NOTRUNC=""
case "$MACHINEARCH" in
i3un*) CONV_NOTRUNC="conv=notrunc" ;;
esac

# Output a string ($1), padded with nulls if necessary to extend it
# to a specified length ($2), and append the result to a file ($3).
NullPaddedString()
{
    NullPadLen=`awk 'BEGIN {
      len = length("'"$1"'")
      if (len > 0) printf "%.'"$2"'s", "'"$1"'" >>"'"$3"'"
      if (len < '"$2"') print '"$2"'-len
      exit
    }'`
    [ -n "$NullPadLen" ] && dd $CONV_NOTRUNC if=$NULLS bs=1 count=$NullPadLen >>$3 2>/dev/null
}

# If caller hasn't supplied a TTA print job header, create one now.
if [ -n "$TTA_PRINT_HEADER" ]; then
  TMPFILE=""
else
  HeaderLen=0
  :>$TMPFILE

  # TTA_USERNAME
  FieldLen=252
  NullPaddedString "$TTA_USERNAME" $FieldLen $TMPFILE
  HeaderLen=`expr $HeaderLen + $FieldLen`

  # TTA_PRINT_FLAGS (Optional value.  If set, it must be a decimal representation
  # of a single byte - ie a value between 0 and 255 inclusive).
  [ -z "$TTA_PRINT_FLAGS" ] && TTA_PRINT_FLAGS=0

  # Convert TTA_PRINT_FLAGS to octal so that we can use it in a shell printf.
  OCTAL_FLAGS=`awk 'BEGIN {
      x='"${TTA_PRINT_FLAGS}"'
      printf "%o\n", x
      exit
  }'`
  FieldLen=4
  printf "\0${OCTAL_FLAGS}\0\0\0" >>$TMPFILE
  HeaderLen=`expr $HeaderLen + $FieldLen`

  # LOGNAME
  FieldLen=34
  NullPaddedString "$LOGNAME" $FieldLen $TMPFILE
  HeaderLen=`expr $HeaderLen + $FieldLen`

  # HOSTNAME
  FieldLen=64
  if [ -n "$real_hostname" ]; then
      NullPaddedString "`$real_hostname`" $FieldLen $TMPFILE
  else
      NullPaddedString "" $FieldLen $TMPFILE
  fi
  HeaderLen=`expr $HeaderLen + $FieldLen`

  # COPIES
  FieldLen=5
  printf `echo "00000${copies}" | sed 's/.*\(.....\)$/\1/'` >>$TMPFILE
  HeaderLen=`expr $HeaderLen + $FieldLen`

  # JOB NAME
  FieldLen=32
  NullPaddedString "`GetTitle \"$title\" \"$1\"`" $FieldLen $TMPFILE
  HeaderLen=`expr $HeaderLen + $FieldLen`

  # TTA PRINTER
  if [ -n "$TTA_PRINTER" ]; then
      # ensure that the preceding field is null-terminated
      FieldLen=1
      printf "\0" >>$TMPFILE
      HeaderLen=`expr $HeaderLen + $FieldLen`
      FieldLen=64
      ActualFieldLen=`expr "$TTA_PRINTER" : '.*'`
      if [ $ActualFieldLen -le $FieldLen ]; then
	  NullPaddedString "`echo "${TTA_PRINTER}" | sed 's/\\\\/&&/g'`" $FieldLen $TMPFILE
      else
	  # Long printer names need to be processed in two chunks ...
	  FieldLenEx=256	# max permitted total printer name length
	  OverflowArea=588	# offset of overflow area
	  ChunkLen=`expr $FieldLen - 1`
	  Chunk1=`echo "$TTA_PRINTER" | cut -b-${ChunkLen}`
	  Chunk2=`echo "$TTA_PRINTER" | cut -b${FieldLen}-`
	  # Output the first chunk of the printer name, followed by a continuation flag
	  NullPaddedString "`echo "${Chunk1}" | sed 's/\\\\/&&/g'`" $ChunkLen $TMPFILE
	  awk 'BEGIN { printf "+%c", '"$OverflowArea"'/4; exit }' >>$TMPFILE
	  # Pad up to the overflow area
	  HeaderLen=`expr $HeaderLen + $ChunkLen + 2`
	  NullPaddedString "" "`expr $OverflowArea - $HeaderLen`" $TMPFILE
	  HeaderLen=$OverflowArea
	  # Output the remainder of the printer name to the overflow area
	  if [ $ActualFieldLen -le $FieldLenEx ]; then
	      FieldLen=`expr $ActualFieldLen - $ChunkLen`
	  else
	      FieldLen=`expr $FieldLenEx - $ChunkLen`
	  fi
	  NullPaddedString "`echo "${Chunk2}" | sed 's/\\\\/&&/g'`" $FieldLen $TMPFILE
      fi
      HeaderLen=`expr $HeaderLen + $FieldLen`
  fi

  # Pad it out to 1024 bytes
  NullPaddedString "" "`expr 1024 - $HeaderLen`" $TMPFILE
fi

#
# Check for printing from stdin and make the filename "-". cat understands
# this to be stdin and we can mingle it on the command line with the header.
#
if [ -z "$1" ]
then
  NEXT='-'
else
  NEXT=$1
fi

# Remove Tarantella directory from PATH before calling real lp{r} command
PATH=`StripPath "$command"` export PATH

#
# Print all the files seperately so they all have our header on them
#
while [ -n "$NEXT" ]
do
  if [ "$NEXT" != "-" -a ! -f "$NEXT" ]
  then
    StdErr "${m_lp_cantopen} $NEXT"
  else
    [ -n "$TTA_PRINT_DEBUG" ] && StdErr "${m_lp_printing1}${printer:-<null>}${m_lp_printing2}${LOGNAME:-<null>}${m_lp_printing3}${TTA_USERNAME:-<null>}"
    case "$command" in
    *lpr) case "$real_command" in
	*lpr) cat $TMPFILE $NEXT | $real_command -P$printer $args ;; # lpr->lpr
	*)    cat $TMPFILE $NEXT | $real_command -d$printer	     # lpr->lp
	esac ;;
    *) case "$real_command" in
	*lpr) cat $TMPFILE $NEXT | $real_command -P$printer ;;	     # lp->lpr
	*)    if [ -z "${options}" ]; then                           # lp->lp
                  cat $TMPFILE $NEXT | $real_command -d$printer $args
              else
                  cat $TMPFILE $NEXT | $real_command -d$printer -o "${options}" $args
              fi
	esac
    esac
  fi

  # Avoid "Cannot shift" error if there are no args. $1 is empty anyway
  [ "$NEXT" != "-" ] && shift
  NEXT=$1
done

#
# Tidy up
#
rm -f $TMPFILE $NULLS >/dev/null 2>&1

exit 0
