#! /bin/sh
#Tag 0x00000700
#**************************************************************************
#*
#* 		  Copyright (c) 1992 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: mkscsipr
#*
#* $Revision: 1.18 $
#*
#* Description: A script to install a System V printer with a SCSI interface.
#*	The script is interactive. The SCSI printer to be installed should
#*	have been powered on before the system was powered on. The script
#*	will permit installation of a SCSI printer that was not on at
#*	system power-on but a warning will be issued.
#*
#*	Usage: mkscsipr
#*
#*	Selection of all installation parameters such as printer name will
#*	be done interactively.
#*
#**************************************************************************


# Well known directories and programs

LPUTIL_DIR=/usr/lib
LPUTIL=$LPUTIL_DIR/lputil

AWK_DIR=/usr/bin
AWK=$AWK_DIR/nawk

OUT_FILT="/usr/bin/pg -s -p more... -e"

DATA_DIR=/usr/lib/print/data
SPOOL_DIR=/var/spool/lp
POD_DIR=$SPOOL_DIR/pod
DUMMYDEV_DIR=$SPOOL_DIR/devices

LPSTAT=/usr/bin/lpstat


# Global variables

PMODEL_LIST=""
PTYPE_LIST=""
POPT_LIST=""
NUM_MODELS=0

PHINV_LIST=""
NUM_HINV=0
NUM_INTR=0

PNAME=""
INTR_NAME=""
UNIT_NUM=""
CTRL_NUM=""
TYPE_ID=""
MODEL_NAME=""
TYPE_NAME=""
DRIVER_PATHNAME=""
DUMMY_DEV=""
SCSI_DEV=""


#
# 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
}


#
# Creates a list of SCSI printers. The list consists of model file
# and name information
#
CreateSCSIList()
{
    list=`$LPUTIL list | $AWK -F\% 'BEGIN { dosep = 0 }
	{
	    if ($2 != "" && $3 != "" && index($2, "SCSI") != 0) {
		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 SCSI printers.
#
ShowSCSIList()
{
    echo "Supported SCSI Printer Types:"
    echo $PTYPE_LIST | $AWK -F\| 'BEGIN { RS = "|" }
	{
	    printf("\t%2d. %s\n", NR, $1)
	}' | $OUT_FILT
}


#
# Creates a list of connected, powered-on SCSI printers
#
CreateSCSIHinv()
{
    PHINV_LIST=`hinv | $AWK -F\: 'BEGIN { dosep = 0 }
	{
	    if ($1 != "" && index($1, "Printer") != 0) {
		n = split($2, arr, " ")
		i = 1
		while (i <= n) {
		    if (arr[i] == "unit") {
			i++
			unit = arr[i]
		    }
		    if (arr[i] == "on") {
			i++
			intr = tolower(arr[i])
		    }
		    if (arr[i] == "controller") {
			i++
			ctrl = arr[i]
		    }
		    i++
		}
		if (dosep)
		    printf("|")
		else
		    dosep = 1
		"/bin/ls /var/spool/lp/member" | getline dcont
		if (length(dcont) != 0) {
		    gline = sprintf("%s_c%dd%d *", intr, ctrl, unit)
		    if (system("cd /var/spool/lp/member; egrep -s "gline) == 0)
		    {
		        "cd /var/spool/lp/member; egrep -l "gline|getline pname
		        printf("%d,%d,%s,%s", ctrl, unit, pname, intr)
		    } else {
		        printf("%d,%d,*,%s", ctrl, unit, intr)
		    }
		} else {
		    printf("%d,%d,*,%s", ctrl, unit, intr)
		}
	    }
	}'`
    NUM_HINV=`echo $PHINV_LIST | $AWK -F\, 'BEGIN { RS = "|"; count = 0 }
	{
	    if ($1 != "")
	        count++
	}
	END { printf("%d\n", count) }'`
    NUM_INTR=`echo $PHINV_LIST | $AWK -F\, 'BEGIN { RS = "|"; count = 0 }
	{
	    if ($1 != "") {
		if (count == 0) {
		    iname = $4
		    count++
		} else {
		    if (iname != $4) {
			iname = $4
			count++
		    }
		}
	    }
	}
	END { printf("%d\n", count) }'`
    if [ $NUM_INTR -eq 1 ]; then
	INTR_NAME=`echo $PHINV_LIST | $AWK -F\, 'BEGIN { RS = "|" }
	    {
	    printf("%s\n", $4)
	    exit 0
	    }'`
    fi
}


#
# Displays a list of connected, powered-on SCSI printers
#
ShowSCSIHinv()
{
    echo "SCSI Printers Detected on:"
    echo $PHINV_LIST | $AWK -F\, 'BEGIN { RS = "|" }
	{
	    printf("\tInterface %s:  controller %d, unit %d", $4, $1, $2)
	    if ($3 != "*")
	        printf(" (installed as \"%s\")", $3)
	    printf("\n")
	}' | $OUT_FILT
}


#
# Search for a (controller, unit) pair from the list of
# connected SCSI printers
#
# Expects $1 to be the interface name, $2 to be controller number
# and $3 to be unit. Returns 0 if found, 1 if not found
#
FindSCSIDev()
{
    echo $PHINV_LIST | egrep -s "$2,$3,.*,$1"
    return $?
}


#
# 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`
}


#
# 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`
}


#
# Extracts the driver pathname from the POD config file
# Model file name is expected as $1
#
GetDriverPathname()
{
    DRIVER_PATHNAME=`$AWK -F\| '/^[ ]*Driver[ ]+Path/ {
	    printf("%s", $2)
	    exit
	}' $DATA_DIR/${1}.config`
}


#
# Changes the Port Path entry in the POD config file to
# the value of $1
#
ChangeConfigPort()
{
    pod_name=$POD_DIR/${PNAME}.config
    $AWK -F\| '{
	    if ($1 ~ /^[ ]*Port[ ]+Path/) {
	        printf("%s| %s\n", $1, scsidev)
	    } else {
		printf("%s\n", $0)
	    }
	}' scsidev=$1 $pod_name > $pod_name.new
    mv $pod_name.new $pod_name
    chown lp.lp $pod_name
    chmod 0644 $pod_name
}


#
# 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 | egrep -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 | egrep -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 valid interface name (i.e. no spaces)
#
VerifyIntrName()
{
    if [ $# -gt 1 ]; then
	return 1
    fi
    return 0
}


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

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

#
# Display an intro message
#
echo "SCSI Printer Installation Tool\n"

#
# Query user for a name for this printer
#
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 max. (A-Za-z0-9_ only)"
	PNAME=""
    fi
    if [ "$PNAME" = "" ]; then
        continue
    fi
    /bin/ls $SPOOL_DIR/member/$PNAME 2> /dev/null 1> /dev/null
    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
echo " "

#
# Look for SCSI printers connected to the system
# and display what we find
#
CreateSCSIHinv
if [ $NUM_HINV -eq 0 ]; then
    echo "WARNING: No SCSI printers appear to be connected to this system."
    echo "         Check that printer power is on and reboot system."
    echo '\nContinue installation (y/n)[n]? \c'
    read yn
    if [ \( "$yn" != "y" \) -a \( "$yn" != "Y" \) ]; then
        exit 1
    fi
else
    ShowSCSIHinv
fi
echo " "

#
# Query user for interface, controller and unit numbers
#
while [ "$INTR_NAME" = "" ]; do
    echo "Enter interface name: \c"
    read INTR_NAME
    VerifyIntrName
    if [ $? -eq 1 ]; then
	echo "Invalid response: Interface name must not contain spaces"
	INTR_NAME=""
    fi
done
while [ "$CTRL_NUM" = "" ]; do
    echo "Enter controller number: \c"
    read CTRL_NUM
    VerifyInt $CTRL_NUM
    if [ $? -eq 1 ]; then
	echo "Invalid response: Controller number must be 0 or greater"
	CTRL_NUM=""
    fi
done
while [ "$UNIT_NUM" = "" ]; do
    echo "Enter unit number: \c"
    read UNIT_NUM
    VerifyInt $UNIT_NUM
    if [ $? -eq 1 ]; then
	echo "Invalid response: Unit number must be 0 or greater"
	UNIT_NUM=""
    fi
done
echo " "

#
# Determine an interface prefix for the specified interface name.
# Add new hinv/board pairs here.
#
if [ "$INTR_NAME" = "vme-scsi" ]; then
    INTR_PRE="jag"
elif [ "$INTR_NAME" = "xylogics" ]; then
    INTR_PRE="xyl"
else
    INTR_PRE="sc"
fi

#
# Verify that the actual SCSI device driver exists
#
SCSI_DEV=/dev/scsi/${INTR_PRE}${CTRL_NUM}d${UNIT_NUM}l0
/bin/ls $SCSI_DEV 2> /dev/null 1> /dev/null
if [ $? -ne 0 ]; then
    echo "WARNING: Device file $SCSI_DEV does not exist."
    echo '\nContinue installation (y/n)[n]? \c'
    read yn
    if [ \( "$yn" != "y" \) -a \( "$yn" != "Y" \) ]; then
        exit 1
    fi
fi

#
# Check whether the interface/controller/unit are in the hinv list
#
FindSCSIDev $INTR_NAME $CTRL_NUM $UNIT_NUM
if [ $? -eq 1 ]; then
    echo "WARNING: Interface $INTR_NAME, controller $CTRL_NUM, unit $UNIT_NUM"
    echo "         does not appear to have a printer connected."
    echo "         Check that printer power is on and reboot system."
    echo '\nContinue installation (y/n)[n]? \c'
    read yn
    if [ \( "$yn" != "y" \) -a \( "$yn" != "Y" \) ]; then
        exit 1
    fi
fi

#
# Look for supported SCSI printer types and display what we find
#
echo " "
echo "Determining supported SCSI printer types..."
echo " "
CreateSCSIList
if [ $NUM_MODELS -eq 0 ]; then
    echo "ERROR: No SCSI printers appear to be supported on this system."
    echo "       Check that SCSI printer software has been installed."
    exit 1
else
    ShowSCSIList
fi
echo " "

#
# Query user for printer type
#
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

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

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

#
# If one does not already exist, create a dummy device file for
# lp to open. The dummy device is just /dev/null (same major and
# minor numbers. We cannot create a link because lputil changes the
# device file permissions and ownership.
#
if [ ! -d $DUMMYDEV_DIR ]; then
    mkdir $DUMMYDEV_DIR
    chmod 755 $DUMMYDEV_DIR
    chown lp.sys $DUMMYDEV_DIR
fi
DUMMY_DEV=$DUMMYDEV_DIR/${INTR_NAME}_c${CTRL_NUM}d${UNIT_NUM}
dev_info=`/bin/ls -l /dev/null`
major_dev=`echo $dev_info|$AWK '{print substr($5,$5,index($5,",")-1)}'`
minor_dev=`echo $dev_info|$AWK '{print $6}'`
rm -f $DUMMY_DEV
/etc/mknod $DUMMY_DEV c $major_dev $minor_dev
chmod 664 $DUMMY_DEV
chown lp.sys $DUMMY_DEV

#
# 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 $DUMMY_DEV $MODEL_NAME $PNAME \
	NAME=\'\"$TYPE_NAME\"\' $OPTION_STR | $AWK '{
        rv = system($0)
	    exit rv
	}'

#
# Now edit the config file to contain the proper
# SCSI device file. The printer driver obtains the
# device file from the config file rather than from
# the spooling system
#
ChangeConfigPort $SCSI_DEV

#
# Change permissions on the actual SCSI device file.
# This way SCSI drivers do not have to be setuid
# root programs. lputil will change the owner and
# permissions back to root when the printer is removed.
#
chown lp.sys $SCSI_DEV
chmod 600 $SCSI_DEV

#
# With the name of the model file we can obtain the
# pathname of the driver by looking at the POD config file
#
GetDriverPathname $MODEL_NAME

#
# Run the driver in update status mode to ensure that config
# and status files reflect installed printer options
#
if [ "$DRIVER_PATHNAME" = "" ]; then
    echo "WARNING: A driver entry could not be found in the POD config file."
    echo "         Check Driver Path entry in $POD_DIR/${PNAME}.config"
elif [ ! -x $DRIVER_PATHNAME ]; then
    echo "WARNING: The driver for this printer is not executable."
    echo "         Check permissions and ownership of $DRIVER_PATHNAME"
else
    $DRIVER_PATHNAME -s -e -P $PNAME
fi

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

#
# Return a successful exit code
#
exit 0
