#!/bin/sh
#Tag 0x00000700
#**************************************************************************
#*
#* 		  Copyright (c) 1993 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: mkserialpr
#*
#* $Revision: 1.5 $
#*
#* Description: Shell script for adding a serial interface printer to
#*	the System V spooling system.
#*
#*	Usage: mkserialpr
#*
#*	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"
SPOOL_DIR=/var/spool/lp
LPSTAT=/usr/bin/lpstat


# Global variables

PNAME=""
DEF_SER_PORT=2
SER_PORT=""
SW_HAND="1"
HW_HAND="2"
DEF_HAND=$SW_HAND
HANDSHAKE=""
BAUD=""
DEF_BAUD="9600"
SW_HAND_PARAMS=""
SER_DEV=""
NUM_MODELS=0
PMODEL_LIST=""
PTYPE_LIST=""
POPT_LIST=""
TYPE_ID=""
TYPE_NAME=""
MODEL_NAME=""
OPTION_STR=""


#
# 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 serial printers. The list consists of model
# file name, printer type and other information
#
CreateSerList()
{
    list=`$LPUTIL list | $AWK -F\% 'BEGIN { dosep = 0 }
	{
	    if ($3 != "" && (length($2) == 0 || index($2, "SERIAL"))) {
		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 serial printers
#
ShowSerList()
{
    echo "Supported Serial Printer Types:"
    echo $PTYPE_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`
}


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


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

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

#
# Display an intro message
#
echo "Serial 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 " "

#
# Query the user for the device port number
#
while [ "$SER_PORT" = "" ]; do
    echo "Enter serial port number [$DEF_SER_PORT]: \c"
    read SER_PORT
    if [ "$SER_PORT" = "" ]; then
	SER_PORT=$DEF_SER_PORT
    else
        VerifyInt $SER_PORT
        if [ $? -eq 1 ]; then
            echo "Invalid response: Serial port must be a number"
	    SER_PORT=""
        fi
    fi
done
echo " "

#
# Query the user for the handshaking method
#
echo "Handshaking method:"
echo "\t1. Software"
echo "\t2. Hardware"
while [ "$HANDSHAKE" = "" ]; do
    echo "Enter handshaking method number [$DEF_HAND]: \c"
    read HANDSHAKE
    if [ "$HANDSHAKE" = "" ]; then
	HANDSHAKE=$DEF_HAND
    else
        VerifyInt $HANDSHAKE
        if [ $? -eq 1 ]; then
            echo "Invalid response: must be 1 or 2"
            HANDSHAKE=""
	    continue
        fi
        if [ \( $HANDSHAKE -lt 1 \) -o \( $HANDSHAKE -gt 2 \) ]; then
            echo "Invalid response: must be 1 or 2"
            HANDSHAKE=""
        fi
    fi
done
echo " "

#
# Query the user for the baud rate
#
echo "Available baud rates: 38400, 19200, 9600, 4800, 2400, 1200, 300"
while [ "$BAUD" = "" ]; do
    echo "Enter baud rate [$DEF_BAUD]: \c"
    read BAUD
    if [ "$BAUD" = "" ]; then
        BAUD=$DEF_BAUD 
    else
        VerifyInt $BAUD
        if [ $? -eq 1 ]; then
            echo "Invalid response: Invalid baud rate"
	    BAUD=""
	    continue
        fi
        if [ $BAUD -eq 0 ]; then
            echo "Invalid response: Baud rate must be greater than 0"
	    BAUD=""
        fi
    fi
done
echo " "

#
# Form the serial port device file pathname
#
if [ $HANDSHAKE -eq $SW_HAND ]; then
    SER_DEV="/dev/ttyd$SER_PORT"
    SW_HAND_PARAMS="STTYPARAMS='\"-ixany ixon ixoff\"'"
else
    SER_DEV="/dev/ttyf$SER_PORT"
fi

#
# Sanity check the device port by seeing if we can ls it
#
/bin/ls $SER_DEV 2> /dev/null 1> /dev/null
if [ $? -ne 0 ]; then
    echo "WARNING: Device file $SER_DEV does not exist."
    echo '\nContinue installation (y/n)[n]? \c'
    read yn
    if [ \( "$yn" != "y" \) -a \( "$yn" != "Y" \) ]; then
	exit 1
    fi
    echo " "
fi

#
# Check to see if another printer is using this port
#
in_use=`cd $SPOOL_DIR/member; egrep -l $SER_DEV * 2> /dev/null`
if [ "$in_use" != "" ]; then
    echo "WARNING: Device file $SER_DEV is currently used by printer(s):"
    for p in $in_use; do
	echo "\t\t$p"
    done
    echo '\nContinue installation (y/n)[n]? \c'
    read yn
    if [ \( "$yn" != "y" \) -a \( "$yn" != "Y" \) ]; then
	exit 1
    fi
    echo " "
fi

#
# Look for supported serial printer types and display what
# we find
#
echo "Determining supported serial printer types..."
echo " "
CreateSerList
if [ $NUM_MODELS -eq 0 ]; then
    echo "ERROR: No serial printers appear to be supported on this system."
    echo "       Check that printer software has been installed."
    exit 1
else
    ShowSerList
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


#
# Inform the user of what comes next
#
echo " "
echo "Installing serial 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

#
# 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 $SER_DEV $MODEL_NAME \
	$PNAME NAME=\'\"$TYPE_NAME\"\' \
	BAUDRATE=$BAUD $SW_HAND_PARAMS $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 "Serial printer $PNAME has been installed"
echo " "
echo "Here is your printing environment:"
echo " "
$LPSTAT -t | $OUT_FILT

#
# Return a successful exit code
#
exit 0
