#!/bin/sh
#  $Id: print_move.sh,v 1.5 2005/07/28 15:31:57 billwe Exp $
#  Copyright (C) 2002-2005 Sun Microsystems, Inc.
#  This software code contains proprietary information 
#  and should be treated as confidential.
#
#  Component: Printing
#  Author:    Bill Weir
#
#  Move queued print jobs from one Tarantella server to another.

# This is a generic product script used to establish an environment
# before starting/stopping a product or component.
# This script was built from shell library
#   $Id: startup.shlib,v 10.165.6.1 2006/04/03 09:51:35 billwe Exp $
# This script has to run on every platform we support.  Any suggestions
# for improvement are welcome (but must be portable!)

# Version numbers
PRODUCT_VERSION="4.2"
PRODUCT_VERSION_FULL="4.20.983"
PRODUCT_VERSION_MAJOR=4
PRODUCT_VERSION_FEATURE=2
PRODUCT_VERSION_BUG=0
PRODUCT_VERSION_BUILD=983
PRODUCT_VERSION_CAB=4,2,0,983

# Product names
PRODUCT_FULL_NAME="Sun Secure Global Desktop Software"
PRODUCT_SHORT_NAME="Secure Global Desktop"
PRODUCT_SHORT_FILENAME="Tarantella"
TSP_FULL_NAME="Sun Secure Global Desktop Security Pack"
TSP_SHORT_NAME="Security Pack"
WCP_FULL_NAME="Sun Secure Global Desktop Windows Connectivity Pack"
WCP_SHORT_NAME="Windows Connectivity Pack"
TN3270_FULL_NAME="Sun Secure Global Desktop Mainframe Connectivity Pack"
TN3270_SHORT_NAME="Mainframe Connectivity Pack"
AS400_FULL_NAME="Sun Secure Global Desktop AS/400 Connectivity Pack"
AS400_SHORT_NAME="AS/400 Connectivity Pack"
S1PSTK_FULL_NAME="Sun Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_FULL_NAME="Sun Secure Global Desktop Integration Pack for Sun ONE Portal Server"
S1PSTK_SHORT_NAME="Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_SHORT_NAME="Secure Global Desktop Integration Pack for Sun ONE Portal Server"

OBJECT_MGR_NAME="Object Manager"
ARRAY_MGR_NAME="Array Manager"
NATIVE_WIN16_FULL_NAME="Sun Secure Global Desktop Native Client for Windows 3.1"
NATIVE_WIN16_SHORT_NAME="Native Client for Windows 3.1"
NATIVE_WIN32_FULL_NAME="Sun Secure Global Desktop Native Client for Windows 95, 98 and NT"
NATIVE_WIN32_SHORT_NAME="Native Client for Windows 95, 98 and NT"
NATIVE_WYSE_FULL_NAME="Sun Secure Global Desktop Native Client for Wyse"
NATIVE_WYSE_SHORT_NAME="Native Client for Wyse"
NATIVE_FULL_NAME="Sun Secure Global Desktop Native Client"
NATIVE_SHORT_NAME="Native Client"
NATIVE_REGISTRY_NAME="Tarantella Native Client"
TCC_FULL_NAME="Sun Secure Global Desktop Client"
TCC_HELPER_NAME="Sun Secure Global Desktop Client Helper"
TCC_ACTIVEX_NAME="Sun Secure Global Desktop ActiveX Control"
TCC_PLUGIN_NAME="Sun Secure Global Desktop Netscape Plug-in"
T3COMPONENT_WIN_NAME="Sun Secure Global Desktop Enhancement Module for Windows"
T3COMPONENT_UNIX_NAME="Sun Secure Global Desktop Enhancement Module for UNIX/Linux"
T3COMPONENT_SHORT_UNIX_NAME="tem"
T3COMPONENT_NAME="Sun Secure Global Desktop Enhancement Module"

# Watch the length of these names: IE refuses to remove packages if
# the name is too long.
ARCHIVE_NAME_ttalw="TCC Helper, version"
ARCHIVE_NAME_asad="3.x Framework Java Archive"
#ARCHIVE_NAME_tta="3.x Java Archive"
#ARCHIVE_NAME_tta="3.x Combined Java Archive"
ARCHIVE_NAME_tta="Client, "
ARCHIVE_NAME_tsp="3.x Security Java Archive"
ARCHIVE_NAME_proxy="3.x Proxy Java Archive"

ARCHIVE_SUFFIX="F"

NS_REGKEY="java/download/com/tarantella/tta"

PRODUCT_VENDOR="Sun Microsystems, Inc."
PRODUCT_SHORT_VENDOR="Sun"

# Capabilities:
# The format for the capabilities required by the client end of a
# connection is: CAPABILITIES_protocol_type_REQUIRED="expression"

# The format for the capabilities provided by the server end of a
# connection is: CAPABILITIES_protocol_type_PROVIDED="c1 c2 ... c3"

# Asad between a webtop client and server:
CAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Asad between two peer servers, or an admin tool and a server:
# 1.1 is core E3 array functionality.
# 1.2 is 3.01 array interoperability functionality.
# 2.1 is core Pisa client device mapping functionality (not a requirement)
CAPABILITIES_ASAD_PEER_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_PEER_PROVIDED="1.1 1.2 2.1"

# Client versions of server strings; same format, name prefixed by CLIENT
# Asad between a webtop client and server:
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"


# be paranoid about the current path
if [ -d /bin ]; then
  PATH=/bin:$PATH
fi
if [ -d /sbin ]; then
  PATH=/sbin:$PATH
fi
if [ -d /usr/bin ]; then
  PATH=/usr/bin:$PATH
fi
if [ -d /usr/sbin ]; then
  PATH=/usr/sbin:$PATH
fi
if [ -d /etc ]; then
  PATH=/etc:$PATH
fi
export PATH

N=""
C=""
if echo -n | grep n > /dev/null
then
  C="\c"
else
  N="-n"
fi
case "$MACHINEARCH" in
i3li*|ppli*) N="$N -e" ;;
esac
_ss_headlines="--------------------------------------------------------------------------"

u="`LANG=C LC_ALL=C id | sed 's/.*uid=\([0-9][0-9]*\).*/\1/'`"
if [ "$u" = "0" ]
then
  : # all is okay
else
  echo "You must be root to run this program"
  exit 15
fi

if [ -z "$0" ]; then
  who_i_am=""
else
  who_i_am=`expr "//$0" : '.*/\(.*\)' `
fi

ttacommand=$0
case "$ttacommand" in
/*) cd `dirname $ttacommand`
    ;;
*)  fullpath=`pwd`/$ttacommand
    cd `dirname $fullpath`
esac

lf_nomessages="No message files installed for LANG="
l_langdefault="Attempting to use default English (en-us) messages"
l_langunknown="Unrecognized \$LANG: "
l_langunset="\$LANG is not set."
lf_langright="Please check the \$LANG variable is correct."
l_langsetto="\$LANG is currently set to: "
l_gottheselangs="Message files are installed for the following languages:"
l_usinglang="Using messages in"
[ -z "$LANG" ] && LANG="C"

TTALANG=$LANG
case "$TTALANG" in
C)  TTALANG="en-us"
    ;;
[a-z][a-z]_[A-Z][A-Z])
    # convert LANG format from ab_CD to ab-cd
    TTALANG=`echo "$TTALANG" | LANG=C LC_ALL=C tr '[A-Z]_' '[a-z]-'`
esac

if [ ! -d $TTALANG -o -z "$TTALANG" ]; then
  [ ! -z "$TTALANG" ] && posslangs=`find . -type d -name "$TTALANG*" -print 2>/dev/null | sed 's;.*\/.*\/.*;;'`

  [ -z "$posslangs" ] && posslangs=`find . -type d -name '[a-z][a-z]-[a-z][a-z]*' -print 2>/dev/null | sed 's;.*\/.*\/.*;;'`

  nposslangs=`echo $posslangs | wc -w`
  if [ "$nposslangs" -gt 1 ]; then
    case "$TTALANG" in
      ??* )
            echo "${lf_nomessages}${LANG}" #!!!
	    echo "$lf_langright"
            ;;
      "" )
           echo "$l_langunset"
           ;;
      * )
          TTALANG=en-us
          echo "$l_langunknown $LANG"
          echo "$l_langdefault"
          ;;
    esac
    echo "$l_gottheselangs"
    tmpTTALANG=$TTALANG
    for a_lang in $posslangs; do
      output=`echo $a_lang | sed -e 's/.*\///'`
      echo "  $output"
      if [ -f $output/common -o -f ../$output/common ]; then
	[ "$tmpTTALANG" != "en-us" ] && tmpTTALANG=$output
      fi
    done
    [ "$TTALANG" = "$tmpTTALANG" ] && TTALANG=en-us || TTALANG=$tmpTTALANG	
    echo "$l_usinglang $TTALANG"
  elif [ "$nposslangs" -eq 1 ]; then
    TTALANG=`echo $posslangs | sed -e 's/.*\///'`
  else
    echo "$lf_reinst"
    exit 5
  fi
fi

TTAMSG=`pwd`/$TTALANG
export TTAMSG TTALANG
if [ $trace ]; then echo "   trace: Language dir = $TTAMSG"; fi

if [ -f $TTAMSG/common -a -f $TTAMSG/print_move ]; then
  . $TTAMSG/common
  . $TTAMSG/print_move
else
  echo "Unable to open message file: $TTAMSG/print_move"
  exit 1
fi


ARCH="@@ARCH@@"
TTADIR="@@TTADIR@@"
OK=t
case "${ARCH}" in
@@*@@) 	OK="";;
*)	case "${TTADIR}" in
	@@*@@) OK=""
	esac
esac
[ -z "${OK}" ] && { echo "Fatal error in $0" >&2; exit 1; }

QUEUEDIR="${TTADIR}/var/print/queue"
TTA_HOST=""
TTA_PRINTER="tta_printer"
APP_PRINTER="tta_prtmove"
CUPS=""
USAGE=""
PRESERVE=""
PRINTCAP_FULL=/etc/printcap
PRINTCAP_LOCAL=/etc/printcap.local

while [ -z "${USAGE}" -a -n "$1" ]; do
    case "$1" in
    --help) 
	echo "${m_longusage}" >&2
	exit 0
        ;;
    --server) 
	TTA_HOST="$2"
	shift
        ;;
    --printer) 
	TTA_PRINTER="$2"
	shift
        ;;
    --cups) 
	case "$2" in
	[${a_case_yes}]*) CUPS=y;  shift;;
	[${a_case_no}]*)  CUPS=n;  shift;;
	${a_auto})        CUPS=""; shift;;
	*)  echo "${m_unknownarg}--cups $2"
	    USAGE="t"
	esac
        ;;
    --preserve) 
	PRESERVE="t"
        ;;
    *)  echo "${m_unknownarg}$1"
	USAGE="t"
    esac
    shift
done

if [ -n "${USAGE}" -o -z "${TTA_HOST}" ]; then
    echo "${m_shortusage}" >&2
    exit 1
fi

cd ${QUEUEDIR}
jobCount=`ls | wc -l`

if [ "${jobCount}" -eq 0 ]; then
    echo "${m_nojobs}" >&2
    exit 0
fi

########################################################################
IsCups()
{
    # Is the installed print system CUPS? (Common UNIX Printing System)
    _yes=0 _no=1
    # Have we been told what to say?
    case "${CUPS}" in
    y) return ${_yes};;
    n) return ${_no};;
    esac
    [ ! -d /etc/cups ] && return ${_no}		# no cups directory
    # Looks like we might have CUPS - look for lpadmin to confirm
    PATH=/usr/sbin:/usr/bin:/etc:${PATH} export PATH
_lpadmin=''
for _dir in `echo "$PATH" | tr : ' '`; do
    case "${_dir}" in
    /*) [ -x "${_dir}/lpadmin" ] && { _lpadmin="${_dir}/lpadmin"; break; }
    esac
done

    [ -z "${_lpadmin}" ] && return ${_no}	# no lpadmin program
    # Finally, look for a running cupsd process
    case "${ARCH}" in
    i3li*|ppli*) _psflags="ajx";;
    *)     _psflags="-ef"
    esac
    _cupsd=`ps ${_psflags} 2>/dev/null | egrep '( |/)cupsd( |$)' | egrep -v egrep`
    [ -z "${_cupsd}" ] && return ${_no}		# cupsd not running
    return ${_yes}
}


########################################################################
IsLPRng()
{
    # LPRng has an "lpc reread" option, so we run "lpc help" to see if it 
    # knows about that option.  There must be a better way ...
    _yes=0 _no=1
_lpc=''
for _dir in `echo "$PATH" | tr : ' '`; do
    case "${_dir}" in
    /*) [ -x "${_dir}/lpc" ] && { _lpc="${_dir}/lpc"; break; }
    esac
done

    [ -z "${_lpc}" ] && return ${_no}
    _msg=`${_lpc} help 2>&1 | grep reread`
    [ -z "${_msg}" ] && return ${_no}
    return ${_yes}
}


getProcessInfo() #######################################################
{
    case "${ARCH}" in
    i3li*|ppli*) processInfo=`ps ajx 2>/dev/null | awk '$2=="'"$1"'"{print}'` ;;
    *)     processInfo=`ps -fp$1 2>/dev/null | awk '$2=="'"$1"'"{print}'`
	   [ -z "$processInfo" ] && processInfo=`ps -ajx 2>/dev/null | awk '$2=="'"$1"'"{print}'`
    esac
    echo "$processInfo"
    return 0
}

LPRngTidy() ############################################################
{
    PATH=/usr/sbin:/usr/bin:/etc:${PATH} export PATH

    # For LPRng we need to tell the running lpd daemon that we have
    # changed the printer configuration.  Hopefully if we are not 
    # running LPRng this command will fail silently.
    #
    # For some unknown reason "lpc reread" sometimes hangs forever, so we
    # run it in background and kill it if it's still around after a minute.
    #
_lpc=''
for _dir in `echo "$PATH" | tr : ' '`; do
    case "${_dir}" in
    /*) [ -x "${_dir}/lpc" ] && { _lpc="${_dir}/lpc"; break; }
    esac
done

    [ -n "${_lpc}" ] && { ${_lpc} reread >/dev/null 2>&1 & pid=$!; }
    for i in 0 1 2 3 4 5 6 7 8 9 A B; do
	processInfo=`getProcessInfo $pid`
	if [ -z "$processInfo" ]; then
	    # process has exited
	    pid=''
	    break
	fi
	sleep 5
    done
    if [ -n "$pid" -a "$pid" != "1" ]; then
	kill $pid 2>/dev/null
	sleep 1
	kill -9 $pid 2>/dev/null
    fi

    # For some other unknown reason "lpc reread" sometimes doesn't work
    # at all, so try sending SIGHUP to the running lpd process.
    case "${ARCH}" in
    i3li*|ppli*) _psflags="ajx" _parentfield=1;;
    *) 	   _psflags="-ef" _parentfield=3
    esac
    _pid=`ps "${_psflags}" 2>/dev/null |
	  egrep '( |/)lpd( |$)' |
	  awk '$'"${_parentfield}"'==1{print $2}'`
    [ -n "${_pid}" ] && kill -1 "${_pid}"


    # Some Linux systems have a checkpc command that fixes things like
    # spool directory permissions.  Its man page says that it may need
    # to be run several times.
_checkpc=''
for _dir in `echo "$PATH" | tr : ' '`; do
    case "${_dir}" in
    /*) [ -x "${_dir}/checkpc" ] && { _checkpc="${_dir}/checkpc"; break; }
    esac
done

    [ -n "${_checkpc}" ]; then
	${_checkpc} -f >/dev/null 2>&1
	${_checkpc} -f >/dev/null 2>&1
	${_checkpc} -f >/dev/null 2>&1
    }
    
    return 0
}

CreateRemotePrinter()
{
    if IsCups; then
	PATH=/usr/sbin:/usr/bin:/etc:${PATH} export PATH
	lpadmin -x ${APP_PRINTER} 2>/dev/null
	lpadmin -p ${APP_PRINTER} -v lpd://${TTA_HOST}/${TTA_PRINTER} -E
	return 0
    fi
    case "${ARCH}" in
    i3li|ppli)
	LPRng="" FORCE_LOCALHOST=""
	IsLPRng && LPRng=t FORCE_LOCALHOST="force_localhost@:"
	SPOOLDIR=''
	# Remove old tta_prtmove entry from printcap (if present)
	for PRINTCAP in ${PRINTCAP_FULL} ${PRINTCAP_LOCAL}; do
	    [ -z "`grep \"^${APP_PRINTER}:\" ${PRINTCAP} 2>/dev/null`" ] && continue
	    TMP_PRINTCAP=${TMPDIR:-/tmp}/prtinst1$$
	    awk '/^'"${APP_PRINTER}"':/ {
		remove = 1
		next
	    }
	    /^[^ 	]/ {
		remove = 0
	    }
	    remove == 0 {
		print
	    }' ${PRINTCAP} >${TMP_PRINTCAP}
	    # make sure we haven't messed up too badly before overwriting printcap
	    # - the only diff should be a section headed by the printer name, and
	    # followed by zero or more parameter lines
	    result=`diff ${PRINTCAP} ${TMP_PRINTCAP} |
		sed -n '/^</s/<[ 	]*//p' |
		awk -F: '{
		    if ((NR == 1 && $1 != "'"${APP_PRINTER}"'") || (NR > 1 && $1 != ""))
			print "FAIL"
		}'`
	    if [ -n "${result}" ]; then
		rm -f ${TMP_PRINTCAP}
		return 1
	    fi
	    if [ -f ${TMP_PRINTCAP} ]; then
		cp ${TMP_PRINTCAP} ${PRINTCAP}
		rm -f ${TMP_PRINTCAP}
	    fi
	done
	if [ -d /var/spool/lpd ]; then
	    SPOOLDIR=/var/spool/lpd
	elif [ -d /usr/spool/lpd ]; then
	    SPOOLDIR=/usr/spool/lpd
	fi
	if [ -n "${SPOOLDIR}" ]; then
	    mkdir "${SPOOLDIR}/${APP_PRINTER}" 2>/dev/null
	    uid=`ls -ld ${SPOOLDIR} | awk '{print $3}'`
	    gid=`ls -ld ${SPOOLDIR} | awk '{print $4}'`
	    chown $uid "${SPOOLDIR}/${APP_PRINTER}" 2>/dev/null
	    chgrp $gid "${SPOOLDIR}/${APP_PRINTER}" 2>/dev/null
	    chmod 775 "${SPOOLDIR}/${APP_PRINTER}" 2>/dev/null
	fi
	# Add new tta_prtmove entry to printcap
	for PRINTCAP in ${PRINTCAP_FULL} ${PRINTCAP_LOCAL}; do
	    echo "${APP_PRINTER}:\\
	:lp=:rm=${TTA_HOST}:rp=${TTA_PRINTER}:sd=${SPOOLDIR}/${APP_PRINTER}:${FORCE_LOCALHOST}" >>${PRINTCAP}
	done
	[ -n "${LPRng}" ] && LPRngTidy
    	;;
    spso|i3so|i3un)
	PATH=${PATH}:/usr/sbin:/usr/bin:/sbin:/etc export PATH
	lpadmin -x ${APP_PRINTER} 2>/dev/null
	lpsystem -tbsd ${TTA_HOST}
	lpadmin -p ${APP_PRINTER} -s"${TTA_HOST}!${TTA_PRINTER}"
	enable ${APP_PRINTER}
	accept ${APP_PRINTER}
    	;;
    pahp)
	PATH=${PATH}:/usr/sbin:/usr/bin:/sbin:/usr/lib export PATH
	lpshut
	lpadmin -x ${APP_PRINTER} 2>/dev/null
	lpadmin -p${APP_PRINTER} -orm${TTA_HOST} -orp${TTA_PRINTER} -ob3 -v/dev/null -mrmodel
	enable ${APP_PRINTER}
	accept ${APP_PRINTER}
	lpsched
    	;;
    rsai)
	PATH=${PATH}:/usr/bin:/etc:/usr/sbin:/sbin export PATH
	device=`lsque -c -q${APP_PRINTER} 2>/dev/null | sed -n "/^${APP_PRINTER}:/!d;s/^${APP_PRINTER}://;s/:.*//p"`
	[ -n "${device}" ] && rmquedev -d${device} -q${APP_PRINTER}
	queue=`lsque -c -q${APP_PRINTER} 2>/dev/null | sed -n "/^${APP_PRINTER}:/!d;s/:.*//p"`
	[ -n "$queue" ] && rmque -q${APP_PRINTER}
	mkque -q${APP_PRINTER} -a "host = ${TTA_HOST}" -a "rq = ${TTA_PRINTER}"
	mkquedev -q${APP_PRINTER} -dremote-${TTA_PRINTER} -a "backend = /usr/lib/lpd/rembak"
	qadm -U ${APP_PRINTER}
    	;;
    esac
    return 0
}

if CreateRemotePrinter; then
    real_lpr="" real_lp=""
    [ -f /usr/bin/lp ]  && real_lp="/usr/bin/lp"
    [ -f /bin/lp ]      && real_lp="/bin/lp"
    [ -f /usr/ucb/lpr ] && real_lpr="/usr/ucb/lpr"
    [ -f /usr/bin/lpr ] && real_lpr="/usr/bin/lpr"
    [ -f /bin/lpr ]     && real_lpr="/bin/lpr"
    ls | while read jobName; do
	case "${ARCH}" in
	i3li|ppli) echo ${real_lpr} -P${APP_PRINTER} ${jobName}
	      ${real_lpr} -P${APP_PRINTER} ${jobName}
	      [ $? -eq 0 -a -z "${PRESERVE}" ] && rm -f ${jobName}
	      ;;
	*)    echo ${real_lp} -c -d${APP_PRINTER} ${jobName}
	      ${real_lp} -d${APP_PRINTER} ${jobName}
	      [ $? -eq 0 -a -z "${PRESERVE}" ] && rm -f ${jobName}
	esac
    done
fi

exit 0
