#!/bin/sh 
#Tag 0x00000700
#**************************************************************************
#*
#* 		  Copyright (c) 1995 Silicon Graphics, Inc.
#*			All Rights Reserved
#*
#*	   THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF SGI
#*
#* The copyright notice above does not evidence any actual of intended
#* publication of such source code, and is an unpublished work by Silicon
#* Graphics, Inc. This material contains CONFIDENTIAL INFORMATION that is
#* the property of Silicon Graphics, Inc. Any use, duplication or
#* disclosure not specifically authorized by Silicon Graphics is strictly
#* prohibited.
#*
#* RESTRICTED RIGHTS LEGEND:
#*
#* Use, duplication or disclosure by the Government is subject to
#* restrictions as set forth in subdivision (c)(1)(ii) of the Rights in
#* Technical Data and Computer Software clause at DFARS 52.227-7013,
#* and/or in similar or successor clauses in the FAR, DOD or NASA FAR
#* Supplement. Unpublished - rights reserved under the Copyright Laws of
#* the United States. Contractor is SILICON GRAPHICS, INC., 2011 N.
#* Shoreline Blvd., Mountain View, CA 94039-7311
#**************************************************************************
#*
#* File: mkjtpr
#*
#* $Revision: 1.1 $
#*
#* Description: Shell script for adding a printer directly connected
#*              to the network to the System V spooling system.  Example
#               are printers connected to HP JetDirect cards.
#*
#*	Usage: mkjtpr  [<local printer name>] 
#                      [<name or IP address of network adaptor>]
#*
#*	Selection of the local model file will always be
#*	done interactively.
#*
#*      ~lp/model/<printer_model> files that contain DEVICE=NETPRINT are
#*      assumed to be valid choices for use with this script.  The user
#*      is offered a list to choose from based on the files that
#*      have the DEVICE=NETPRINT string.
#*
#**************************************************************************


# Well known directories and programs

LPUTIL_DIR=/usr/lib
LPUTIL=$LPUTIL_DIR/lputil
APPRES=/usr/bin/X11/appres
AWK_DIR=/usr/bin
AWK=$AWK_DIR/nawk
PING_CMD="/usr/etc/ping -q -c3"
ARP_CMD="/usr/etc/arp"
GREP_CMD="/bin/egrep"
OUT_FILT="/usr/bin/pg -s -p more... -e"
SPOOL_DIR=/var/spool/lp
INTERFACE_DIR=$SPOOL_DIR/interface
LPSTAT=/usr/bin/lpstat
CHKCONFIG=/sbin/chkconfig 
OUTSOCK="OUTSOCK"  # An option in the model file that we update.
INSOCK="INSOCK" # An option in the model file that we update.

# Global variables

PNAME=""
NUM_MODELS=0
NUM_DEVICES=0
PMODEL_LIST=""
PTYPE_LIST=""
POPT_LIST=""
TYPE_ID=""
PORT_ID=""
OUT_PORT_NUMBER=""
IN_PORT_NUMBER=""
TYPE_NAME=""
MODEL_NAME=""
OPTION_STR=""
REMOTE_HOST=""
DEV_LIST=""
OUT_PORTS=""
IN_PORTS=""

#
# Prints the program usage string
#
PrintUsage()
{
    echo "Usage: mkjtpr [<local printer name>] [<name or IP address of network adaptor>]"
}

#
# Checks that we are the super-user and verifies
# that the System V spooling system is present
#
CheckPermSpooler()
{
    cid=`/usr/bin/id | $AWK '{print substr($1,index($1,"("))}'`;
    if [ "$cid" != "(root)" ]; then
        echo "You must be logged in as root to use this program."
        exit 1;
    fi
    if [ ! -r $SPOOL_DIR ]; then
        echo "The System V spooling system is not installed on this system."
        exit 1
    fi
}

#
# Create a list of valid network card devices.  This pulls the data
# from the Printers resource file.
CreateNetDeviceList()
{
string=`$APPRES Printers | $GREP_CMD -i netprinter | $GREP_CMD -i "\*NETPRINTER\*netDevices" | $GREP_CMD ","`

DEV_LIST=`echo $string | $AWK -F\| '{print substr($1,index($1,"Network"))}' | nawk -F\% ' BEGIN { dosep = 0 } 
        {
            size=split($1,a,",")
            count=1
            mod=0
            while(count<=size) {
               if (mod==0) {
                  if (dosep)
                       printf("|")
                   else
                       dosep = 1
                  printf("%s", a[count])
               }
               mod+=1
               if (mod==3) mod=0
               count+=1
            }
        }'`

OUT_PORTS=`echo $string | $AWK -F\| '{print substr($1,index($1,"Network"))}' | nawk -F\%  ' BEGIN { dosep = 0 }  
        {
            size=split($1,a,",")
            count=1
            mod=0
            while(count<=size) {
               if (mod==1) {
                  if (dosep)
                       printf("|")
                   else
                       dosep = 1
                   sub(" ","",a[count])
                   printf("%s", a[count])
               }
               mod+=1
               if (mod==3) mod=0
               count+=1
            }
        }'`


IN_PORTS=`echo $string | $AWK -F\| '{print substr($1,index($1,"Network"))}' | nawk -F\%  ' BEGIN { dosep = 0 }
        {
            size=split($1,a,",")
            count=1
            mod=0
            while(count<=size) {
               if (mod==2) {
                  if (dosep)
                       printf("|")
                   else
                       dosep = 1
                   sub(" ","",a[count])
                   printf("%s", a[count])
               }
               mod+=1
               if (mod==3) mod=0
               count+=1
            }
        }'`


NUM_DEVICES=`echo $string | $AWK -F\| '{print substr($1,index($1,"Network"))}' | nawk -F\| '
        {
            size=split($1,a,",")
        } 
        END { printf("%d\n", size/3) }'`

}


#
# If a list of network cards and network adaptors could not be parsed
# from the Printers resource file in CreateNetDeviceList then build a default 
# list that lists the HP cards.
#
BuildDefaultList()
{
DEV_LIST="Network Card Installed in Printer|HP JetDirect EX External Interface|HP JetDirect EX Plus3 Port 1|HP JetDirect EX Plus3 Port 2|HP JetDirect EX Plus3 Port 3"

OUT_PORTS="-1|9100|9100|9101|9102"
IN_PORTS="-1|9100|9100|9101|9102"

NUM_DEVICES="5"

}

#
# Creates a list of network printers. The list consists of model
# file name, printer type and other information
#
CreateNetList()
{
    list=`$LPUTIL list | $AWK -F\% 'BEGIN { dosep = 0 }
	{
	    if ($3 != "" &&
		    (length($2) == 0 ||
		     index($2, "NETPRINT"))) {
		if (dosep)
		    printf("|")
		else
		    dosep = 1
		if (NF > 3)
		    printf("%s%%%s%%%s", $1, $3, $4)
		else
		    printf("%s%%%s%%", $1, $3)
	    }
	}'`
    PMODEL_LIST=`echo $list | $AWK -F\% 'BEGIN { RS = "|"; dosep = 0 }
	{
	    if (dosep)
		printf(" ")
	    else
		dosep = 1
	    printf("%s", $1)
	}'`
    PTYPE_LIST=`echo $list | $AWK -F\% 'BEGIN { RS = "|"; dosep = 0 }
	{
	    if (dosep)
		printf("|")
	    else
		dosep = 1
	    printf("%s", $2)
	}'`
    POPT_LIST=`echo $list | $AWK -F\% 'BEGIN { RS = "|"; dosep = 0 }
	{
	    if (dosep)
		printf("|")
	    else
		dosep = 1
	    printf("%s", $3)
	}'`
    NUM_MODELS=`echo $list | $AWK -F\% 'BEGIN { RS = "|"; count = 0 }
	{
	    if ($1 != "")
		count++
	}
	END { printf("%d\n", count) }'`
}


#
# Displays a list of network printers
#
ShowNetList()
{
    echo "Supported Network Printer Types:"
    echo $PTYPE_LIST | $AWK -F\| 'BEGIN { RS = "|" }
	{
	    printf("\t%2d. %s\n", NR, $1)
	}' | $OUT_FILT
}

ShowNetDeviceList()
{
    echo "Supported Network Interface Types:"
    echo $DEV_LIST | $AWK -F\| 'BEGIN { RS = "|" }
        {
            printf("\t%2d. %s\n", NR, $1)
        }' | $OUT_FILT
}


#
# Extracts the model file name from the model file list
# given $1 is the index into the list
#
GetModelFileName()
{
    MODEL_NAME=`echo $PMODEL_LIST | $AWK '{
            printf("%s\n",$i)
        }' i=$1`
}


#
# Extracts the printer type from the type list
# given $1 is the index into the list
#
GetPrinterType()
{
    TYPE_NAME=`echo $PTYPE_LIST | $AWK -F\| '{
            printf("%s\n",$i)
        }' i=$1`
}

#
# Extract the TCP port number to use 
#
GetOutPortNumber()
{
    OUT_PORT_NUMBER=`echo $OUT_PORTS | $AWK -F\| '{
            printf("%s\n",$i)
        }' i=$1`
}

#
# Extract the TCP port number to use
#
GetInPortNumber()
{
    IN_PORT_NUMBER=`echo $IN_PORTS | $AWK -F\| '{
            printf("%s\n",$i)
        }' i=$1`
}


#
# Extracts the printer model file options string
# from the list given $1 is the index into the list
#
GetPrinterOptions()
{
    OPTION_STR=`echo $POPT_LIST | $AWK -F\| '{
            printf("%s\n",$i)
        }' i=$1`
}


#
# Test for pure decimal positive integer input
#
# Expects $1 to be the value to check. Returns 0 if
# OK, 1 if invalid positive integer or if more than one
# argument specified
#
VerifyInt()
{
    if [ $# -eq 0 ]; then
	return 0
    fi
    if [ $# -gt 1 ]; then
	return 1
    fi
    echo $1 | $GREP_CMD -s '^[0-9]*$'
    return $?
}


#
# Test for a valid printer name (i.e. 14 chars max, A-Za-z0-9_
# only and no spaces)
#
VerifyPname()
{
    if [ $# -gt 1 ]; then
	return 1
    fi
    echo $1 | $GREP_CMD -s '^[A-Za-z0-9_]*$'
    if [ $? -eq 1 ]; then
	return 1
    fi
    if [ `echo $1 | $AWK '{ print length($1) }'` -gt 14 ]; then
	return 1
    else
	return 0
    fi
}

#
# Test for a properly constructed remote host name
#
VerifyHostname()
{
    if [ $# -gt 1 ]; then
        return 1
    fi
    return 0
}

# Check if we can ping the network card.  We can't do anything fancy
# like connect to it since it will refuse connections if it is busy
# printing.  This just makes sure it is on the net and can be pinged.

checkjetonnet()
{

  if $CHKCONFIG network; then
     :
  else
     echo "Networking has not been enabled on this system." 1>&2
     return 1
  fi

  host=$1

  # See if we can ping it.  We really use this to add an arp entry for the
  # network device (ping will not return an error if there is an ARP entry    
  # even if it could not ping the device).
 
  $PING_CMD $host 2> /dev/null 1> /dev/null

  if [ $? != 0 ]; then
     echo "Printer $host name not known.  Check /etc/hosts or yp server entries." 1>&2
     return 1
  fi

  # Check the arp table to make sure we really got it.  NOTE: If printer was 
  # on net and then removed it is possible there is still an ARP entry.  As
  # long as there is an ARP entry we continue.            

  arp_string=`$ARP_CMD "$host"` 2> /dev/null 

  echo $arp_string | $GREP_CMD "no entry" >> /dev/null 
  if [ $? != 1 ]; then
     echo "Could not ping network printer: $host.  Check network \nconnection to printer."
     return 1
  fi

  echo $arp_string | $GREP_CMD "incomplete" >> /dev/null 
  if [ $? != 1 ]; then
     echo "Could not ping network printer: $host.  Check network \nconnection to printer."
     return 1
  fi

  return 0

}


# Check for a duplicate printer name. Returns 0 if dup,
# 1 if name is unique
#
CheckDupName()
{
    /bin/ls $SPOOL_DIR/member/$1 2> /dev/null 1> /dev/null
    return $?
}


#
# Query user for a name for the local printer
#
QueryLocalName()
{
    while [ "$PNAME" = "" ]; do
        echo "Enter new printer name (14 chars max.): \c"
        read PNAME
        VerifyPname $PNAME
        if [ $? -eq 1 ]; then
            echo "Invalid response: Name must be 14 chars (A-Za-z0-9_ only)"
            PNAME=""
        fi
        if [ "$PNAME" = "" ]; then
            continue
        fi
        CheckDupName $PNAME
        if [ $? -eq 0 ]; then
            echo " "
            echo "WARNING: Printer $PNAME already exists."
            echo '\nChoose a new name (y/n)[y]? \c'
            read yn
            if [ \( "$yn" != "n" \) -a \( "$yn" != "N" \) ]; then
                PNAME=""
            fi
        fi
    done
}


#########################################################################
#
# Main program
#

#
# Ensure that we are root and that the main System V
# spooling system directory is present
#
CheckPermSpooler

#
# Get command line arguments, if any.
#
case $# in
    0) ;;
    1) PNAME=$1
       ;;
    2) PNAME=$1
       REMOTE_HOST=$2
       ;;
    *) PrintUsage
       exit 1
       ;;
esac
#
# Make sure we have a remote printer host
#
if [ "$REMOTE_HOST" = "" ]; then
    while [ "$REMOTE_HOST" = "" ]; do
        echo "Enter remote printer name (network name or IP address): \c"
        read REMOTE_HOST
        VerifyHostname $REMOTE_HOST
        if [ $? -eq 1 ]; then
            echo "Invalid response: Improperly constructed hostname"
            REMOTE_HOST=""
        fi
    done
    echo " "
fi

echo "Testing connection to printer: $REMOTE_HOST...\n"

checkjetonnet $REMOTE_HOST
if [ $? -eq 1 ]; then
   echo "\nContinue anyway using $REMOTE_HOST as remote printer name(y/n)[y]? \c"
   read yn
   if [ \( "$yn" != "y" \) -a \( "$yn" != "Y" \) ]; then
      exit 1
   fi
fi

#
# Query user for a name for this printer
#
if [ "$PNAME" = "" ]; then
    QueryLocalName
    echo " "
else
    echo "Requested local printer name: $PNAME\n"
    VerifyPname $PNAME
    if [ $? -eq 1 ]; then
        echo "Error: Local printer name must be 14 chars max (A-Za-z0-9_ only)"
        PNAME=""
        QueryLocalName
        echo " "
    fi
    CheckDupName $PNAME
    if [ $? -eq 0 ]; then
        echo " "
        echo "WARNING: Printer $PNAME already exists."
        echo '\nChoose a new name (y/n)[y]? \c'
        read yn
        if [ \( "$yn" != "n" \) -a \( "$yn" != "N" \) ]; then
            PNAME=""
            QueryLocalName
            echo " "
        fi
    fi
fi

echo " "
#
# Look for supported network printer types and display what
# we find
#
echo "Determining supported network printer types..."
echo " "
CreateNetList
if [ $NUM_MODELS -eq 0 ]; then
    echo "ERROR: None of the printer drivers installed on this system support"
    echo "       driving a network printer.  Check the model scripts in "
    echo "       /var/spool/lp/model.  Printers that are supported will have "
    echo "       the string\" DEVICE=NETPRINT\" near the top of the model file."
    echo " "
    echo "       Note that this script attempts to setup a driver that directly"
    echo "       drives the network printer.  You might wish to spool files to"
    echo "       a remote workstation that, in turn, will forward them to the"
    echo "       network printer.  Use the mknetpr script to do that."
    exit 1
else
    ShowNetList
fi
echo " "

#
# Query user for printer type to install
#
while [ "$TYPE_ID" = "" ]; do
    echo "Enter printer type number: \c"
    read TYPE_ID
    VerifyInt $TYPE_ID
    if [ $? -eq 1 ]; then
        echo "Invalid response: Type must be number between 1 and $NUM_MODELS"
        TYPE_ID=""
    fi
    if [ "$TYPE_ID" = "" ]; then
	continue
    fi
    if [ \( $TYPE_ID -eq 0 \) -o \( $TYPE_ID -gt $NUM_MODELS \) ]; then
        echo "Invalid response: Type must be between 1 and $NUM_MODELS"
        TYPE_ID=""
    fi
done

#
# Look for names of network devices (JetDirect, built-in card, etc. )
# 
echo ""
echo "Determining supported network interface cards..."
echo ""
CreateNetDeviceList
if [ $NUM_DEVICES -eq 0 ]; then
    BuildDefaultList
fi
ShowNetDeviceList

echo " "

#
# Query user for network interface type 
#
while [ "$PORT_ID" = "" ]; do
    echo "Enter interface type number: \c"
    read PORT_ID
    VerifyInt $PORT_ID
    if [ $? -eq 1 ]; then
        echo "Invalid response: Type must be number between 1 and $NUM_DEVICES"
        PORT_ID=""
    fi
    if [ "$PORT_ID" = "" ]; then
        continue
    fi
    if [ \( $PORT_ID -eq 0 \) -o \( $PORT_ID -gt $NUM_MODELS \) ]; then
        echo "Invalid response: Type must be between 1 and $NUM_DEVICES"
        PORT_ID=""
    fi
done

#
# Inform the user of what comes next
#
echo " "
echo "Installing printer $PNAME..."
echo " "

#
# Given the type ID we can extract the model file name from the
# model list, the type from the type list and the options from the
# options list
#
GetModelFileName $TYPE_ID
GetPrinterType $TYPE_ID
GetPrinterOptions $TYPE_ID
GetOutPortNumber $PORT_ID
GetInPortNumber $PORT_ID

if [ "$OUT_PORT_NUMBER" != "-1" ]; then
  OPTION_STR="$OPTION_STR $OUTSOCK=$OUT_PORT_NUMBER"
fi

if [ "$IN_PORT_NUMBER" != "-1" ]; then
  OPTION_STR="$OPTION_STR $INSOCK=$IN_PORT_NUMBER"
fi

#
# Install the printer. We use awk to execute the lputil command
# because we want the OPTION_STR strings handled properly (i.e.
# with the proper quoting).  
#
echo $LPUTIL add /var/spool/lp/devices/jet $MODEL_NAME $PNAME \
            NETPRINTER=\'\"$REMOTE_HOST\"\'     \
            NAME=\'\"$TYPE_NAME\"\' $OPTION_STR | $AWK '{
	    rv = system($0)
	    exit rv
	}'
if [ $? -ne 0 ]; then
    echo "ERROR: Installation of new printer failed."
    echo "       $LPUTIL command failed."
    exit 1
fi

#
# Inform the user of what has happened
#
echo " "
echo "Network Printer $PNAME has been installed"
echo " "
echo "Here is your printing environment:"
echo " "
$LPSTAT -t | $OUT_FILT

# Give user some background info on trouble-shooting, etc.

echo ""
echo ""
echo "Trouble shooting tips:"
echo ""
echo "If you have problems printing to the network printer first verify"
echo "that you can ping the printer with the command:"
echo " "
echo "  $PING_CMD $REMOTE_HOST"
echo " "
echo "If the ping fails verify that the printer is connected and configured"
echo "correctly (this includes setting the IP address, netmask, etc. on"
echo "the printer).  Some printers must be power-cycled after setting up"
echo "their network card."
echo " "
echo "If you can ping the network printer but can not print then you may"
echo "also need to verify that the TCP port number used to connect to"
echo "the network printer (or network adaptor) is correct.  The port "
echo "number that the print spooler will use to communicate with the network"
echo "printer is specified in the printer model file.  This command will "
echo "return the port number in use: "
echo " "
echo "     $GREP_CMD $OUTSOCK $INTERFACE_DIR/$PNAME | $GREP_CMD -v NET"
echo " "
echo "This command returns:"
echo " "
$GREP_CMD $OUTSOCK $INTERFACE_DIR/$PNAME | $GREP_CMD -v NET
echo " "
echo "You might verify with your printer vendor that the TCP port number "
echo "listed above is correct.  Edit this file to change the port number:"
echo " "
echo "     $INTERFACE_DIR/$PNAME "
echo " "
echo "You can also turn on debugging and print with this command:"
echo " "
echo "  lp -d$PNAME -overbose /etc/group"
echo " "
echo "Debug messages from the print job are logged to: $SPOOL_DIR/log"

#
# Return a successful exit code
#
exit 0
