#! /usr/local/bin/bash
# -*- sh -*-

#
# $ApsCVS: src/apsfilter/SETUP.in,v 1.123.2.11 2002/02/24 20:47:45 andreas Exp $
#
# apsfilter setup tool
#
# written by Andreas Klemm <andreas@apsfilter.org>
# modified for V6.0 by Michael Loin <phallobst@web.de>
#

#
# exit status 0 on successfull printer installation
# exit status 1 indicates failures or if the user simply quit the program
#

PATH="/usr/local/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/bin:/bin"
: ${TMPDIR:=/tmp} ${AWK:=/usr/local/bin/gawk}

APS_TMPDIR="$TMPDIR/apsfilter$$"
rm -rf "$APS_TMPDIR"
mkdir -m 700 "$APS_TMPDIR"
if [ $? -ne 0 ]; then
    APS_TMPDIR=`mktemp -q -d "$TMPDIR/apsfilter.XXXXXX"` || \
	echo 1>&2 "SETUP error: couldn't create temporary directory"
    chmod 700 "$APS_TMPDIR"
fi
export TEMP="$APS_TMPDIR" TMPDIR="$APS_TMPDIR" PATH

trap 'rm -rf "$APS_TMPDIR"' 0


#
# display text with a pager like "more"
#
do_pager()
{
    case "$1" in
	-)		${PAGER-more} ;;
	*.Z)		zcat "$1" | ${PAGER-more} ;;
	*.gz|*.z)	gzip -cd "$1" | ${PAGER-more} ;;
	*)		${PAGER-more} < "$1" ;;
    esac
}             

##############################################################################
# Copyright note and license
##############################################################################
do_copyright()
{
    clear
    cat << !EOM
      _/_/                         _/_/ _/ _/   _/
   _/    _/ _/_/_/     _/_/_/   _/        _/ _/_/_/_/   _/_/   _/  _/_/
  _/_/_/_/ _/    _/ _/_/     _/_/_/_/ _/ _/   _/     _/_/_/_/ _/_/
 _/    _/ _/    _/     _/_/   _/     _/ _/   _/     _/       _/
_/    _/ _/_/_/   _/_/_/     _/     _/ _/     _/_/   _/_/_/ _/
        _/
       _/

    Hi, welcome to the apsfilter setup and thanks for using apsfilter!

    Before we begin with the setup, I'd like to make you familiar
    with the apsfilters license:
    1. apsfilter follows the GNU public license (GPL), see COPYRIGHT
    2. and this little "Postcard License":

	"I'd like to get a postcard from you! I'm interested in,
	 who is using apsfilter, where you live, and where in the
	 world apsfilter is doing it's job."

    Please send me an e-mail to  apsfilter-snailmail@apsfilter.org  to
    get my postal address; we'll get there later in this setup...

!EOM
    echo $n "Accept license [Y|y|J|j|N|n] ? $c"; read answer
    echo
    case $answer in
	Y|y|J|j)
	    echo "License accepted, thanks!"
	    echo
	    sleep 2
	    ;;
	*)
	    echo "License not accepted -- sorry, terminating setup..."
	    exit 1
	    ;;
    esac
}

##############################################################################
# Request snail mail address for "Postcard License"
##############################################################################
do_request_snailmail()
{
    clear
    cat << !EOM
    _/      _/          _/ _/                         _/_/
   _/_/  _/_/   _/_/_/    _/              _/_/_/   _/       _/_/_/
  _/  _/  _/ _/    _/ _/ _/ _/_/_/_/_/ _/       _/_/_/_/ _/    _/
 _/      _/ _/    _/ _/ _/            _/         _/     _/    _/
_/      _/   _/_/_/ _/ _/              _/_/_/   _/       _/_/_/ _/
                                                            _/
                                                       _/_/

Is Internet Mail up and running on *this* machine to request my postal
address to follow the rules of the "Postcard License" ?

!EOM
    echo $n "Request my snail mail address now [Y|y|N|n] ? $c"; read answer
    echo
    case $answer in
	Y|y|J|j)
	    # Find out mail address...
	    while [ -z "$EMAIL_OK" ]; do
		echo
		echo "To what address may I send you my postal address?" 
		echo "Does mail to \"$USER@$HOST\" reach you?"
		echo
		echo "Enter RETURN to accept or type in your"
		echo $n "complete mail address: $c"; read $read_r answer
		if [ -z "$answer" ]; then
		    # use $USER@$HOST
		    REPLYTO="$USER@$HOST"
		    echo
		    echo "Thanks, using $REPLYTO ..."
		    sleep 2
		    echo
		    EMAIL_OK=true
		else
		    # check for fqdn and use his address
		    case $answer in
			*@*.*)
			    REPLYTO="$answer"
			    echo "using $REPLYTO ..."
			    sleep 2
			    EMAIL_OK=true
			    ;;
			*)
			    echo
			    echo "!!! $answer is not a valid !!!"
			    echo "!!! e-mail address....     !!!"
			    sleep 2
			    ;;
		    esac
		fi
	    done

	    { 
		echo "To: apsfilter-snailmail@apsfilter.org"
		echo "Reply-To: $REPLYTO"
		echo "Subject: get snailmail for apsfilter version 7.2.2"
	    } | "/usr/sbin/sendmail" apsfilter-snailmail@apsfilter.org
	    touch .requested_snailmail
	    ;;
	*)
	    echo
	    echo "o.k. for now ..."
	    echo
	    echo "... but please don't forget to request it later ..."
	    sleep 4
	    ;;
    esac
}

##############################################################################
# START SEQUENCE
# - introduce apsfilter, version, copyright
##############################################################################
do_start()
{
    clear
    cat << !EOM
        ================================================================
			  A P S F I L T E R  V 7.2.2
			*** The Unix Print Solution ***
        ================================================================

                       copyright Andreas Klemm, 1993-2002

                              andreas@apsfilter.org

			    http://www.apsfilter.org/

                    ----------------------------------------
                      for Unix systems with BSD compatible 
                          line printer scheduler (lpd)
				or with LPRng
                       FreeBSD / NetBSD / OpenBSD / BSDI
                        Linux and other flavours of Unix
                    ----------------------------------------

			++++ INSTALLATION PROGRAM ++++

                        [ press <RETURN> to continue ]
!EOM
    read answer
    clear
    cat << !EOM
        ================================================================
          A P S F I L T E R   S E T U P               -- PROGRAM INFO --
        ================================================================

        This SETUP script supports the user/administrator by

		- configuring serial/parallel/remote printers
		- creating printer spool directories as needed
		- auto-creation of printcap config-file
		  for apsfilter (add / overwrite printer)
		- setting up apsfilter (which gs driver to use,
		  paper size, print resolutions and color depth)
		- printing a test page (settings may be modified
		  until successfull ouput of a testpage)
		- saves some SETUP settings in apsfilterrc config file

        it does not:

		- complete printer management in printcap
		  (delete/modify printer)
        ----------------------------------------------------------------

                        [ press <RETURN> to continue ]
!EOM
    read answer
}

##############################################################################
# Check which ghostscript release we have
# Now we can offer gs version dependent
#	- driver description
#	- driver selection
##############################################################################
do_check_gs_version()
{
    GS_VERSION=`gs --version`
    case $GS_VERSION in
	7*)
	    GS_BASE=7.00 ;;
	6.[5-9]*)
	    GS_BASE=6.50 ;;
	*)
	    GS_BASE=6.50

	    cat <<EOF
Found ghostscript version $GS_VERSION ...
You have to upgrade at least to gs version 6.50!
But you should upgrade to gs 7.00 for full driver support
prior installing printers with SETUP.
EOF
	    echo $n "Do you you want to continue? [Y/n] $c"; read answer
	    case $answer in
		N|n)
		    echo "o.k., terminating."
		    exit 1
		    ;;
	    esac
	    ;;
    esac
}

##############################################################################
# if user selects a "non-PS printer" and if ghostscript is not installed
# (needed by do_choose_driver)
##############################################################################
warn_about_missing_gs()
{
    clear
    cat << !EOM
    ================================================================
    A P S F I L T E R   S E T U P                      -- WARNING --
    ================================================================

    Attention 
    =========
    As I see now, you are installing apsfilter for a printer that needs
    gs (ghostscript) as postscript emulator, but apsfilter's SETUP was
    unable to locate the ghostscript emulator.

    One reason might be that ghostscript is installed in an unusual
    directory and SETUP was unable to auto-detect this path.

    Then please add this path at the top of SETUP and run it again.

    Otherwise you have to get the ghostscript sources and fonts
    and install ghostscript by hand and run setup again afterwards.
!EOM
    exit 1
}

##############################################################################
# Show the ghostscript devices that are compiled into gs (pretty-print).
##############################################################################

show_gs_devices()
{
    {
	echo "Devices known to ghostscript version $GS_VERSION:"; echo
	gs -q -dNODISPLAY -c "devicenames == quit" | tr -d "/[]" | \
	tr " " "\n" | sort | pr -5 -t -w 80
    } | do_pager -
}

##############################################################################
# Loop until suitable driver found and confirmed by the user
##############################################################################
do_choose_driver()
{
    clear
    cat << !EOM
    ================================================================
			PRINTER DRIVER SELECTION
    ================================================================

    Please select the type of printer you want to install:

    1)  PostScript printer (generic)
    2)  PostScript printer (with ghostscript drivers)
    3)  printer driver natively supported by ghostscript
    4)  gimp-print / stp
    5)  hpdj
    6)  pcl3 (successor to hpdj)
    7)  IBM Omni
    8)  various HP Deskjet drivers
    9)  PPA printer
    10) official HP DeskJet drivers (hpijs 0.97)
    11) official HP DeskJet drivers (hpijs 1.0)
    12) Epson printer (official drivers)
    13) Lexmark inkjet printer
    14) miscellaneous other drivers
    15) non-printer devices (caution! -- read the handbook)

    0)  return to main menu

!EOM
    echo $n "Your choice: $c"; read answer
    case $answer in
	1)	PRINTER=PS; return ;;
	2)	PRINTER=PSgs
		check_for_gs_support pswrite psgray psmono || do_choose_driver
		return ;;
	3)	PRINTER_LIST=setup/printer-$GS_BASE ;;
	4)	PRINTER_LIST=setup/printer-stp ;;
	5)	PRINTER_LIST=setup/printer-hpdj ;;
	6)	PRINTER_LIST=setup/printer-pcl3 ;;
	7)	PRINTER_LIST=setup/printer-omni ;;
	8)	PRINTER_LIST=setup/printer-cdj ;;
	9)	PRINTER_LIST=setup/printer-ppa ;;
	10)	PRINTER_LIST=setup/printer-hpijs ;;
	11)	PRINTER_LIST=setup/printer-ijs ;;
	12)	PRINTER_LIST=setup/printer-epson ;;
	13)	PRINTER_LIST=setup/printer-lexmark ;;
	14)	PRINTER_LIST=setup/printer-misc ;;
	15)	PRINTER_LIST=setup/non-printer ;;
	*)	return ;;
    esac

    # for sanity checks in while loop
    # no of entries in PRINTER_LIST
    MAXNO=`grep -c -v "^#" $PRINTER_LIST`

    clear
    cat <<!EOM

Choose printer driver from the following list; remember the number.

Hint: Navigation in more:
    SPACE    - page down
    b        - backward one screen
    RETURN   - line forward
    /pattern - search for pattern (i.e.: driver name)
    k        - backward one line
    G        - jump to end of file
    1G       - jump to beginning of file
    q        - quit browsing file
    h        - help

Press <RETURN> to continue
!EOM
    read answer

    PRINTER=""
    while [ -z "$PRINTER" ]; do
	# list available gs driver preceeded by number
	grep -v "^#" $PRINTER_LIST \
	    | "$AWK" -F "|" '{ printf("%d - %s [%s]\n", FNR, $1, $2) }' \
	    | do_pager -
	echo "Which driver do you want to choose?"
	echo "[Hit RETURN to see the list again, enter 0 to choose new type.]"
	echo
	echo $n "Enter number: $c"; read answer
	if [ -z "$answer" ]; then
	    : # show the list again
	elif [ $answer = 0 ]; then
	    # choose a different printer type
	    do_choose_driver
	    return
	elif [ $answer -lt 1 -o $answer -gt $MAXNO ]; then
	    echo "wrong selection: enter value between 1 and $MAXNO !"
	    sleep 2
	else
	    # get the driver specified by number
	    PRINTER="`grep -v "^#" $PRINTER_LIST \
			| "$AWK" -F "|" "{ if (FNR == $answer) print \\$2 }"`"
	fi

	# check if gs has this driver compiled in
	if [ -n "$PRINTER" ]; then
	    case "$PRINTER" in
		# print-to-file drivers
		bmp)	check_for_gs_support bmp32b bmpgray bmpmono ;;
		jpeg)	check_for_gs_support jpeg jpeggray ;;
		pcx)	check_for_gs_support pcx24b pcxgray pcxmono ;;
		png)	check_for_gs_support png16m pnggray pngmono ;;
		pnm)	check_for_gs_support ppmraw pgmraw pbmraw ;;
		tiff)	check_for_gs_support tiff24nc tiffpack ;;

		# printer drivers
		*.upp)	check_for_gs_support uniprint ;;
		ppa/*|printiva|lexmark1100)
			check_for_gs_support ppmraw pgmraw pbmraw ;;
		stp/*|omni/*|hpdj/*|pcl3/*|hpijs/*|ijs/*)
			check_for_gs_support "${PRINTER%%/*}" ;;
		lexmark2030|lexmark2070|samsung85)
			check_for_gs_support pbmraw ;;
		lexmark2050c|lexmark2070c|lexmarkZ11)
			check_for_gs_support bitcmyk ;;
		cjet)
			check_for_gs_support ljet3 ;;
		ljet4l)
			check_for_gs_support ljet4 ;;
		stylewriter)
			check_for_gs_support bitcmyk pbmraw ;;
		pips/*)
			check_for_gs_support png16m pnggray pngmono ;;
		st800)
			check_for_gs_support stcolor ;;
		bjc50|bjc70|bjc4000|bjc7000)
			check_for_gs_support bjc600 ;;

		# simple default for printer and non-printer devices
		*)	check_for_gs_support "$PRINTER" ;;
	    esac
	fi

	if [ -n "$PRINTER" ]; then
	    echo
	    echo "You selected driver: $PRINTER"
	    echo
	    echo "Driver $PRINTER supports the following printer(s):"
	    grep "|$PRINTER$" $PRINTER_LIST
	    echo
	    echo $n "Do you want to use $PRINTER? [Y|n] $c"; read answer
	    case $answer in
		N|n)	PRINTER="" ;;
	    esac
	fi
    done
}

check_for_gs_support()
{
    local req

    # check for gs
    type gs >/dev/null 2>&1 || warn_about_missing_gs

    for req; do
	# check if gs has driver compiled in
	if ! gs -h | sed -e '1,/Available devices:/d' -e '/Search path:/,$ d' \
		| grep -w "$req" >/dev/null; then
	    cat <<EOF

Error: Your gs version doesn't have driver "$req" compiled in...
Select another driver or build a new gs version with complete or customized
driver support.

Now you'll see a list of drivers supported by your gs version...

Press <RETURN> to continue
EOF
	    read answer
	    show_gs_devices
	    # to enter selection loop
	    PRINTER=""
	    return 1
	fi
    done
    return 0
}

##############################################################################
# called by do_setup_interface (parallel setup)
##############################################################################
do_ask_parallel_device()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Parallel Interface Settings     -- Device --
        ----------------------------------------------------------------

	Depending on your flavour of Unix, you have to enter the
	*full path* to your parallel Interface. In case of trouble please
	contact your local system administrator or read your operating
	systems technical documentation, FreeBSD handbook or Linux HowTo.
	Some examples:

	FreeBSD, NetBSD, OpenBSD:   LPT1: /dev/lpt0   LPT2: /dev/lpt1
		USB under *BSD:           /dev/ulpt0        /dev/ulpt1
		USB (no reset):           /dev/unlpt0       /dev/unlpt1
	Linux:                      LPT1: /dev/lp0    LPT2: /dev/lp1
		with devfsd:              /dev/printers/0   /dev/printers/1
		USB under Linux:          /dev/usb/lp0      /dev/usb/lp1
	SunOS4:                           /dev/bpp0         /dev/bpp1

	currently selected:               Interface:  [$INTERFACE]
                                          Device:     [$DEVICE]	

!EOM
    echo $n "Full path of parallel print device: $c"; read $read_r answer
    [ "$answer" ] && DEVICE="$answer"

    if [ ! -c "$DEVICE" ]; then
	echo; echo "Warning! Device node '$DEVICE' is not a character"
	echo $n "device. Proceed anyway (y/n)? $c"; read $read_r answer
	[ "$answer" != y -a "$answer" != Y ] && unset DEVICE
    fi
}

##############################################################################
# called by do_setup_interface (remote printer setup)
##############################################################################
do_ask_remote_printer()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Remote Printer SETUP via lpd print protocol
        ----------------------------------------------------------------

	If you have FreeBSD (3.x or later) with an enhanced lpd or
	another Unix System with LPRng, it's possible to use apsfilter
	with remote printer. Restrictions of original Berkeley lpd
	made it impossible in the past, to use lineprinter input filter
	when printing to a remote printer.

	Please enter the full qualified hostname or IP address of the
	remote system as well as the remote printer name.
	See the manpage: printcap(5). Fields "rm" and "rp"

	currently selected:
	machine name for remote printer : [ $rm ]
	remote printer name             : [ $rp ]	

!EOM
    echo $n "Machine name for remote printer: $c"; read $read_r rm
    echo
    echo "Hint for remote printing onto network printer with HP JetDirect card"
    echo "Enter 'raw' as remote printer queuename !"
    echo
    echo $n "Remote Printer Name: $c"; read $read_r rp
    [ "$rm" ] && DEVICE="$rm"
}

##############################################################################
# called by do_setup_interface (samba printer setup)
##############################################################################
do_ask_samba_printer()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Samba Printer SETUP
        ----------------------------------------------------------------

	Take care that smbclient is in apsfilters search path.
	You can fine tune paths in $CONF_DIR/apsfilterrc.
	See smbclient manual page for more options if needed.

	currently selected:
	NetBIOS name of Windows Server  : [ $SMB_SERVER ]
	Windows Server IP               : [ $SMB_IP ]	
	Printer Share  Name             : [ $SMB_PRINTER ]	
	Workgroup                       : [ $SMB_WORKGROUP ]	
	Windows Username                : [ $SMB_USER ]	
	Windows Password                : [ $SMB_PASSWD ]	

	(you can fine tune some more values in the smbclient.conf
	file in the printer's configuration directory later)

!EOM
    echo $n "NetBIOS name of Windows Server: $c"; read $read_r SMB_SERVER
    echo $n "Windows Server IP Address     : $c"; read $read_r SMB_IP
    echo $n "Printer Share Name            : $c"; read $read_r SMB_PRINTER
    echo $n "Workgroup Name                : $c"; read $read_r SMB_WORKGROUP
    echo $n "Print as Windows GUEST user (no: use real account)? [y/n] $c"
    read answer
    case $answer in
	n|N)
	    echo $n "Windows Username              : $c"
	    read $read_r SMB_USER
	    echo $n "Windows Password              : $c"
	    read $read_r SMB_PASSWD
	    ;;
	*)
	    echo "O.K. using user GUEST, to print on Windows Printer..."
	    SMB_USER=""; SMB_PASSWD=""
	    ;;
    esac

    [ "$SMB_SERVER" ] && DEVICE="$SMB_SERVER"
}

##############################################################################
# called by do_setup_interface (netware printer setup)
##############################################################################
do_ask_netware_printer()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   NetWare Printer SETUP
        ----------------------------------------------------------------

	Take care that ncprint/nprint is in apsfilters search path.
	You can fine tune paths in $CONF_DIR/apsfilterrc.
	See ncprint/nprint manual page for more options if needed.

	currently selected:
	NetWare server name  : [ $NCP_SERVER ]
	Printer queue name   : [ $NCP_PRINTER ]
	NetWare username     : [ $NCP_USER ]
	NetWare password     : [ $NCP_PASSWD ]

	(you can fine tune some more values in the netware.conf
	file in the printer's configuration directory later)

!EOM
    echo $n "NetWare server name  : $c"; read $read_r NCP_SERVER
    echo $n "Printer queue name   : $c"; read $read_r NCP_PRINTER
    echo $n "NetWare username     : $c"; read $read_r NCP_USER
    echo $n "NetWare password     : $c"; read $read_r NCP_PASSWD

    [ "$NCP_SERVER" ] && DEVICE="$NCP_SERVER"
}

##############################################################################
# called by do_setup_interface (apple remote printer setup)
##############################################################################
do_ask_atalk_printer()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   AppleTalk Remote Printer SETUP
        ----------------------------------------------------------------

	Take care that pap is installed in apsfilters search path.
	You can fine tune paths in $CONF_DIR/apsfilterrc.
	See pap manual page for more options if needed.

	currently selected:
	NBP name of Apple Printer  : [ $PAP_NBPNAME ]

!EOM
    echo $n "Name (NBP Name) of Apple Printer: $c"; read $read_r PAP_NBPNAME

    [ "$PAP_NBPNAME" ] && DEVICE="$PAP_NBPNAME"
}

##############################################################################
# Some routines for serial interface options, line discipline...
##############################################################################
do_read_serial_device()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Serial Interface Settings       -- Device --
        ----------------------------------------------------------------

	Depending on your flavour of Unix, you have to enter the
	*full path* to your serial Interface. In case of trouble please
	contact your local system administrator or read your operating
	systems technical documentation, FreeBSD handbook or Linux HowTo.
	Some examples:

	FreeBSD, NetBSD, OpenBSD:   COM1: /dev/cuaa0  COM2: /dev/cuaa1
	Linux:                      COM1: /dev/ttyS0  COM2: /dev/ttyS1
	SunOS4:                           /dev/ttya         /dev/ttyb

	currently selected:                    Interface: [$INTERFACE]
                                               Device   : [$DEVICE]
!EOM
    echo $n "Your choice? $c"; read $read_r answer
    [ "$answer" ] && DEVICE="$answer"

    if [ ! -c "$DEVICE" ]; then
	echo; echo "Warning! Device node '$DEVICE' is not a character"
	echo $n "device. Proceed anyway (y/n)? $c"; read $read_r answer
	[ "$answer" != y -a "$answer" != Y ] && unset DEVICE
    fi
}

do_read_serial_baud()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Serial Interface Settings     -- Baudrate --
        ----------------------------------------------------------------

	The Baud Rate is the transfer rate at which the asynchronous
	serial interface is sending bits from the computer to the printer.

	The higher the Baudrate the better and shorter your cable should
	be. I recommend 5m cable as a maximum for 38400 Baud and perhaps
	2-3m for speeds higher than that. It depends heavily on the
	quality of your cables, interfaces, handshaking and printer.

	Another rule of thumb is, that hardware handshaking works best
	with higher Baudrates, but needs a special cable depending on
	your machine and the printer.

	Valid and useable Baudrates are (a good starting point is 9600)

	1) 4800		2) 9600		3) 19200
	4) 38400	5) 57600	6) 115200

	Please note: you have to configure your printer as well for that
	speed and don't forget to power off and on the printer after that.

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  BAUDRATE=4800      	;;
	2)  BAUDRATE=9600	;;
	3)  BAUDRATE=19200	;;
	4)  BAUDRATE=38400	;;
	5)  BAUDRATE=57600	;;
	6)  BAUDRATE=115200	;;
    esac
}

do_read_serial_handshake()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Serial Interface Settings  -- Handshaking --
        ----------------------------------------------------------------

	There are two possible handshaking methods, often called
	Hardware and Software handshaking. This determines, how
	the printer tells your computers start or stop sending data
	to avoid data lossage.

	Directly forget about using ghostscript as Postscript Emulator
	with the software handshaking (xon/xoff protocol), because gs
	(ghostscript) sends a binary data stream to the printer containing
	these start/stop characters. But I will allow you to select this
	as an option, you'll certainly know better than I what you want.

	Hardware handshaking isn't as standardized as it could. So
	different computer/printers use different pins/signals of the
	serial interface, to stop/start the data transfer. You'll
	certainly need a special printer cable !

	1 - software handshaking (xon/xoff, 3 wires, avoid this)
	2 - hardware handshaking (crtscts, RTS/CTS flow control)

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  HANDSHAKE="ixon,ixoff,ixany,-crtscts"
	    HANDSHAKE_FOR_COMMAND="ixon ixoff ixany -crtscts"
	    ;;
	2)  HANDSHAKE="-ixon,-ixoff,-ixany,crtscts"
	    HANDSHAKE_FOR_COMMAND="-ixon -ixoff -ixany crtscts"
	    ;;
    esac
}

do_read_serial_wordlength()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Serial Interface Settings   -- Wordlength --
        ----------------------------------------------------------------

	Computer and Printer must have the same settings how many
	"bits" long a "data word" is.

	We have to use "8 Bit" long data words, otherwise it isn't
	possible to transmit characters above a value of 127.
	We need 8 Bit here!

	1)	8 Bit		(a must !)
	2)	7 Bit		(please do not use this !)

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  WORDLENGTH=8; WORDLENGTH_COMMAND=cs8 ;;
	2)  WORDLENGTH=7; WORDLENGTH_COMMAND=cs7 ;;
    esac
}

do_read_serial_parity()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Serial Interface Settings       -- Parity --
        ----------------------------------------------------------------

	Computer and Printer must have the same settings if they
	use parity or not. Parity is a kind of a checksum to detect
	garbage on the line.

	Usually we use no parity. If there is a need for parity,
	you have to decide if you use even or odd parity.

	1)	no parity	(take this)
	2)	even
	3)	odd

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  PARITY="no parity"; PARITY_COMMAND=-parenb ;;
	2)  PARITY="even"; PARITY_COMMAND="parenb -parodd" ;;
	3)  PARITY="odd"; PARITY_COMMAND="parenb parodd" ;;
    esac
}

do_read_serial_stopbits()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   Serial Interface Settings    -- Stop Bits --
        ----------------------------------------------------------------

	Your computer and printer must have the same amount of stopbits
	configured that are sent/accepted after transmitting a "Data
	word" - and parity information, if you selected one -.

	Standard is to use one stopbit. Please configure your printer's
	serial interface to use one stopbit, if possible, otherwise use
	two stopbits.

	1)	1 Stopbit
	2)	2 Stopbits

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  STOPBITS=1; STOPBIT_COMMAND=-cstopb ;;
	2)  STOPBITS=2; STOPBIT_COMMAND=cstopb ;;
    esac
}

##############################################################################
# called by do_setup_interface (serial setup)
##############################################################################
do_ask_serial_settings()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P    -- Serial Interface Settings --
        ----------------------------------------------------------------

	Important for a successfull configuration is, that the computers
	_and_ the printers interface do have exactly the same settings !

	Operating system dependent
	   1) Printer device			[$DEVICE]

	General operating characteristics
	   2) Baud rate				[$BAUDRATE]
	   3) Handshaking			[$HANDSHAKE]

	Data format
	   4) Data Word Length (in bits)	[$WORDLENGTH]
	   5) Parity				[$PARITY]
	   6) Stopbits				[$STOPBITS]
	   7) Startbits (UNIMPLEMENTED)		[$STARTBITS]

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  do_read_serial_device	;;
	2)  do_read_serial_baud		;;
	3)  do_read_serial_handshake	;;
	4)  do_read_serial_wordlength	;;
	5)  do_read_serial_parity	;;
	6)  do_read_serial_stopbits	;;
    esac
}

##############################################################################
# Print Device serial or parallel?
##############################################################################
do_setup_interface()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P              -- Interface Setup --
        ----------------------------------------------------------------

	The easiest way, to connect a printer to your computer is by
	using the parallel interface, because it's usually *faster*,
	more standardized and therefore much easier to configure.

	When configuring a serial printer, the installation dialogue
	asks you many questions about how to configure the serial
	interface of your computer, so that it works well with your
	printers current settings.

	When using the serial interface, then you have to choose special
	cables, depending on the communication protocol between computer
	and printer (hardware/software handshaking). Many pitfalls here !

	currently selected:               Interface:  [$INTERFACE]
                                          Device:     [$DEVICE]	
	configure local / remote printer
	1) local parallel/USB		2) local serial
	3) Unix/network printer (lpd)	4) Windows / NT (samba)
	5) AppleTalk                    6) Novell NetWare

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	2)  INTERFACE=serial; do_ask_serial_settings ;;
	3)  INTERFACE=network; do_ask_remote_printer ;;
	4)  INTERFACE=samba; do_ask_samba_printer ;;
	5)  INTERFACE=atalk; do_ask_atalk_printer ;;
	6)  INTERFACE=netware; do_ask_netware_printer ;;
	*)  INTERFACE=parallel; do_ask_parallel_device ;;
    esac
    [ "$DEVICE" ] || unset INTERFACE
}

##############################################################################
# Choose the print resolution
##############################################################################
do_choose_resolution()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P             -- Print Resolution --
        ----------------------------------------------------------------

	You can set the default printing resolution here, but keep in
	mind that the quality setting (right now: $QUALITY) has
	greater priority for most drivers.

	You must set the resolution in this dialog for PostScript
	printers (PS, PSgs) and for drivers that don't have a driver
	script (e.g. uniprint profiles).

	Some typical settings to play with:

	1) 150dpi	2) 300dpi	3) 600dpi	4) 1200dpi
	5) 180dpi	6) 360dpi	7) 360x180dpi	8) 720dpi

	c) custom settings

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  XRESOL=150;  YRESOL=150 ;;
	2)  XRESOL=300;  YRESOL=300 ;;
	3)  XRESOL=600;  YRESOL=600 ;;
	4)  XRESOL=1200; YRESOL=1200 ;;
	5)  XRESOL=180;  YRESOL=180 ;;
	6)  XRESOL=360;  YRESOL=360 ;;
	7)  XRESOL=360;  YRESOL=180 ;;
	8)  XRESOL=720;  YRESOL=720 ;;
	*)  # custom settings
	    echo $n "Please input x-resolution in dpi: $c"; read XRESOL
	    echo $n "Please input y-resolution in dpi: $c"; read YRESOL
	    if [ -z "$XRESOL" ]; then
		if [ -z "$YRESOL" ]; then
		    XRESOL=300; YRESOL=300
		else
		    XRESOL=$YRESOL
		fi
	    else
		[ "$YRESOL" ] || YRESOL=$XRESOL
	    fi
	    ;;
    esac
    RESOLUTION=${XRESOL}x${YRESOL}
}

##############################################################################
# Choose default color mode
##############################################################################
do_choose_color()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P                  -- Color Setup --
        ----------------------------------------------------------------

	Please choose whether you want to print in full color, grayscale
	or monochrome mode. Not all drivers support all of these three
	modes.

	If you don't know what to do, use "full color".


	1)	full color mode		(usually 24bpp or 32bpp)
	2)	grayscale mode		(usually 3bpp, 4bpp or 8bpp)
	3)	monochrome mode		(usually 1bpp)

	0)	keep setting [$COLOR]

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)	COLOR=full ;;
	2)	COLOR=gray ;;
	3)	COLOR=mono ;;
    esac
}

##############################################################################
# Choose default printing quality
##############################################################################
do_choose_quality()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P                -- Quality Setup --
        ----------------------------------------------------------------

	This sets the printing quality. Usually, this has an impact on
	the printing resolution and the dithering quality. For some
	drivers, some modes are merely aliases for other modes.

	1)	draft	(usually: lowest resolution, fastest dithering)
	2)	low	(usually: low resolution, fast dithering)
	3)	medium	(usually: medium resolution, normal dithering)
	4)	high	(usually: high resolution, good dithering)
	5)	photo	(usually: highest resolution, best dithering)

	0)	keep setting [$QUALITY]

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)	QUALITY=draft ;;
	2)	QUALITY=low ;;
	3)	QUALITY=medium ;;
	4)	QUALITY=high ;;
	5)	QUALITY=photo ;;
    esac
}

##############################################################################
# Choose default printing method
##############################################################################
do_choose_method()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P                 -- Method Setup --
        ----------------------------------------------------------------

	Please choose how apsfilter should handle the incoming data.

	1)	auto	(automatic data conversion)
	2)	ascii	(treat everything as text)
	3)	raw	(do not modify data; ignores paper size,
			 quality, color and resolution settings)

	0)	keep setting [$METHOD]

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)	METHOD=auto ;;
	2)	METHOD=ascii ;;
	3)	METHOD=raw ;;
    esac
}

##############################################################################
# Choose paper size
##############################################################################
do_setup_paper_format()
{
    clear
    cat << !EOM
	----------------------------------------------------------------
        A P S F I L T E R   S E T U P                 -- Paper Format --
        ----------------------------------------------------------------

	What paper format do you want to use for printing?

	1) DIN A4	(21.0cm x 29.7cm)
	2) DIN A3	(29.7cm x 42.0cm)
	3) US letter	( 8.5in x 11.0in)
	4) US legal	( 8.5in x 14.0in)
	5) US tabloid	(11.0in x 17.0in)
	6) US ledger	(17.0in x 11.0in)

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  PAPER=a4 ;;
	2)  PAPER=a3 ;;
	3)  PAPER=letter ;;
	4)  PAPER=legal ;;
	5)  PAPER=tabloid ;;
	6)  PAPER=ledger ;;
    esac
}

do_print_test_page()
{
    local sv_printer sv_resolution gs_device paper

    sv_printer=$PRINTER; sv_resolution=$RESOLUTION
    [ "$PAPER" = tabloid ] && paper=11x17 || paper="$PAPER"

    # the tmp file containing the print data
    # a) PS content if you have a PS printer
    # b) gs output (translated PS file) using printer driver of your choice

    TESTOUT="$APS_TMPDIR/test_page.aps"

    ### call driver script to adjust options
    unset GS_FEATURES POST_FILTER POST_FILTER_OPTS GS_MODEL
    DRIVER_SCRIPT="$PRINTER"
    if [ ! -e "driver/$DRIVER_SCRIPT" ]; then
	# get the script name from the mapping file
	DRIVER_SCRIPT=$(grep ":$PRINTER:" "driver/MAPPING" | sed "s/:.*//")
    fi
    if [ -n "$DRIVER_SCRIPT" -a -e "driver/$DRIVER_SCRIPT" ]; then
	. "driver/$DRIVER_SCRIPT"
    fi

    # construct test print command, that will be evaluated later; idea is to
    # separate time to create print data and actual time to print it

    case "$PRINTER" in
	omni/*|hpijs/*)
	    GS_FEATURES="$GS_FEATURES -sDeviceName=${PRINTER#*/}"
	    PRINTER=${PRINTER%%/*} ;;
	stp/*|hpdj/*)
	    GS_MODEL=${PRINTER#*/}; PRINTER=${PRINTER%%/*} ;;
	pcl3/*)
	    GS_FEATURES="$GS_FEATURES -sSubdevice=${PRINTER#pcl3/}"
	    PRINTER=pcl3 ;;
	ijs/*)
	    GS_FEATURES="$GS_FEATURES -sDeviceModel='${PRINTER#ijs/}' -sIjsServer=hpijs"
	    PRINTER=ijs ;;
    esac
    case "$PRINTER" in
	PS)
	    # real PS printer
	    CREATE_TESTPAGE_CMD="cp setup/test.ps '$TESTOUT'"
	    ;;
	*.upp)
	    # uniprint profiles
	    CREATE_TESTPAGE_CMD="gs -q -dBATCH -dNOPAUSE -dPARANOIDSAFER \
		-dSAFER @$PRINTER -sPAPERSIZE=$paper -sOutputFile='$TESTOUT' \
		setup/test.ps"
	    ;;
	*)
	    # generic drivers
	    CREATE_TESTPAGE_CMD="gs -q -dBATCH -dNOPAUSE -dPARANOIDSAFER \
		-dSAFER -r$RESOLUTION -sDEVICE=$PRINTER -sPAPERSIZE=$paper \
		${GS_MODEL:+-sModel=$GS_MODEL} $GS_FEATURES $PS_INIT \
		-sOutputFile='$TESTOUT' setup/test.ps"
	    ;;
    esac

    # reset settings (might have been mangled by the driver script)
    PRINTER=$sv_printer; RESOLUTION=$sv_resolution

    # maybe we need an additional filter (e.g. pnm2ppa)
    if [ "$POST_FILTER" ]; then
	if type "$POST_FILTER" > /dev/null 2>&1; then
	    CREATE_TESTPAGE_CMD="$CREATE_TESTPAGE_CMD | '$POST_FILTER' \
		$POST_FILTER_OPTS"
	else
	    echo
	    echo "ERROR: additional filter '$POST_FILTER' was not found;"
	    echo "       can't create test page"
	    echo
	    echo "[ press RETURN to continue ]"
	    read answer
	    return
	fi
    fi

    # Tell the magic command ...
    echo
    echo "Printing Test page using:"
    echo "$CREATE_TESTPAGE_CMD"
    echo
    echo $n "Ok to print testpage? [y/n] $c"; read answer
    case $answer in
	N|n)
	    # do nothing
	    ;;
	*)
	    # print...
	    echo
	    echo "Creating test page..."
	    date >> perf.log
	    echo "$PRINTER $RESOLUTION $QUALITY $COLOR" >> perf.log
	    echo "Time for ghostscript:" >> perf.log

	    # for time to be saved into logfile
	    # stderr has to be redir. before pipe
	    eval time $CREATE_TESTPAGE_CMD 2>&1 | tee -a perf.log

	    # check if command was successful
	    # only then print
	    EXIT_STATUS=$?
	    if [ "$EXIT_STATUS" = 0 ]; then
		echo
		echo "Printing test page... "
		echo "Time for printer:" >> perf.log
		if [ "$INTERFACE" = samba ]; then
		    if [ -n "$SMB_USER" ]; then
			export PASSWD="$SMB_PASSWD"
			SMB_LOGIN="-U ${SMB_USER}"
		    else
			SMB_LOGIN=""
		    fi
		    PRINT_TESTP_CMD="smbclient < '$TESTOUT' \
			//${SMB_SERVER}/${SMB_PRINTER} ${SMB_IP:+-I $SMB_IP} \
			${SMB_LOGIN} ${SMB_WORKGROUP:+-W} ${SMB_WORKGROUP} \
			-b 1400	-N -c 'print -'"
		elif [ "$INTERFACE" = netware ]; then
		    # hide password in temporary configuration file
		    if type ncprint >/dev/null 2>&1; then
			PRINT_TESTP_CMD=ncprint
			{
			    echo "[${NCP_SERVER}:${NCP_USER}]"
			    echo "password=$NCP_PASSWD"
			} > "$APS_TMPDIR/.nwfsrc"
			chmod 600 "$APS_TMPDIR/.nwfsrc"
		    else
			PRINT_TESTP_CMD=nprint
			echo "$NCP_SERVER/$NCP_USER ${NCP_PASSWD:--}" \
			    > "$APS_TMPDIR/.nwclient"
			chmod 600 "$APS_TMPDIR/.nwclient"
		    fi
		    PRINT_TESTP_CMD="$PRINT_TESTP_CMD < '$TESTOUT' \
			-S $NCP_SERVER -U $NCP_USER -q $NCP_PRINTER"
		elif [ "$INTERFACE" = atalk ]; then
		    PRINT_TESTP_CMD="pap -e -p '$PAP_NBPNAME' < '$TESTOUT'"
		elif [ "$INTERFACE" = network ]; then
		    PRINT_TESTP_CMD="lpr -P'${rp}@${rm}' '$TESTOUT'"
		else
		    PRINT_TESTP_CMD="cat '$TESTOUT' > $DEVICE"
		fi

		ls -l "$TESTOUT" | tee -a perf.log
		# temporarily set HOME for NetWare printing commands
		HOME="$APS_TMPDIR" eval time $PRINT_TESTP_CMD 2>&1 | \
		    tee -a perf.log
		echo "[ press RETURN to continue ]"
		read answer
	    else
		echo "last command terminated with exit status: $EXIT_STATUS"
		echo "Error creating testpage!"
		echo "[ press RETURN to continue ]"
		read answer
	    fi
	    ;;
    esac
    # remove temporary files
    rm -f "$TESTOUT" "$APS_TMPDIR/.nwfsrc" "$APS_TMPDIR/.nwclient"
}

do_print_test_menue()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P                    -- Test Page --
        ----------------------------------------------------------------

	In most cases it's relatively easy to choose a suitable
	ghostscript driver from the list of supported printers.

	If you're printer is not in the list of supported printers:
	    - guess a suitable driver by "trial and error"
	    - consult your printers handbook to what ghostscript printer
	      driver your printer "claims" to be compatible

	If this test produces unacceptable results, then please choose
	another driver or try another (perhaps lower) print quality,
	because it might be a memory problem. Only use print resolutions
	that are supported by your printer, consult the printers manual!

	Creating the test output might take some time, please be patient.

	T)  Print a test page
	*)  Back to main menue

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	t|T)  do_print_test_page ;;
    esac
}

do_view_perflog()
{
    if [ -f perf.log ]; then
	do_pager perf.log
    else
	do_pager - << !EOM

You'll have to print a test page first.

!EOM
    fi
}

do_save_environment()
{
    #
    # Save some settings for another SETUP attempt ...
    # Gooood for testing ;-))
    #
    cat > SETUP.cfg <<EOF
CONF_DIR='$CONF_DIR'
PRINTER='$PRINTER'
RESOLUTION='$RESOLUTION'
COLOR='$COLOR'
PAPER='$PAPER'
METHOD='$METHOD'
QUALITY='$QUALITY'
INTERFACE='$INTERFACE'
DEVICE='$DEVICE'
BAUDRATE='$BAUDRATE'
HANDSHAKE='$HANDSHAKE'
WORDLENGTH='$WORDLENGTH'
PARITY='$PARITY'
STARTBITS='$STARTBITS'
STOPBITS='$STOPBITS'
SMB_SERVER='$SMB_SERVER'
SMB_IP='$SMB_IP'
SMB_PRINTER='$SMB_PRINTER'
SMB_WORKGROUP='$SMB_WORKGROUP'
SMB_USER='$SMB_USER'
SMB_PASSWD='$(echo $SMB_PASSWD | sed "s/'/'\\\''/g")'
NCP_SERVER='$NCP_SERVER'
NCP_PRINTER='$NCP_PRINTER'
NCP_USER='$NCP_USER'
NCP_PASSWD='$(echo $NCP_PASSWD | sed "s/'/'\\\''/g")'
rm='$rm'
rp='$rp'
EOF
    if [ "${SMB_PASSWD}${NCP_PASSWD}" ]; then
	echo "read protect SETUP.cfg, since it contains password..."
	chmod 600 SETUP.cfg
	chown root:$LP_GROUP SETUP.cfg
    fi
}

do_main_menue()
{
    MENU_DONE=""

    while [ -z "$MENU_DONE" ]; do
	# printer that need a special PS init file in GS_LIBDIR
	case $PRINTER in
	    stcolor)	PS_INIT=stcolor.ps ;;
	    *)		PS_INIT="" ;;
	esac

	clear
	#
	# display the main menu
	#
	cat << !EOM
        ==================================================================
          A P S F I L T E R   S E T U P                   -- MAIN MENUE --
        ==================================================================

	(D)	Available Device Drivers in your gs binary
	(R)	Read Ghostscript driver documentation        (devices.txt)

	(1)	Printer Driver Selection		[$PRINTER]
	(2)	Interface Setup				[$INTERFACE]
	(3)	Paper Format				[$PAPER]
	(4)	Printing Quality			[$QUALITY]
	(5)	Color Mode				[$COLOR]
	(6)	Print Resolution in "dots per inch"	[$RESOLUTION]
	(7)	Default Printing Method			[$METHOD]

!EOM

	if [ -z "$PRINTER" -o -z "$INTERFACE" -o -z "$PAPER" ]; then
		# you need to set PRINTER, INTERFACE and PAPER before
		# anything else can be done
		unset proceed
		cat << !EOM
	(A)	Abort installation (don't do anything)
	(Q)	==> Finish installation

!EOM
	else
		proceed=true
		cat << !EOM
	(T)	Print Test Page
	(V)	View performance log (times of print attempts)

	(A)	Abort installation (don't do anything)
	(I)	==> Install printer with values shown above - repeat this
		    step for installing multiple printers
	(Q)	==> Finish installation

!EOM
	fi
	echo $n "        Your choice? $c"; read answer
	case $answer in
	    d|D)	show_gs_devices ;;
	    r|R)	do_pager setup/devices-$GS_BASE ;;
	    1)		do_choose_driver ;;
	    2)		do_setup_interface ;;
	    3)		do_setup_paper_format ;;
	    4)		do_choose_quality ;;
	    5)		do_choose_color ;;
	    6)		do_choose_resolution ;;
	    7)		do_choose_method ;;
	    t|T)	[ "$proceed" ] && do_print_test_menue ;;
	    v|V)	[ "$proceed" ] && do_view_perflog ;;
	    a|A)	exit 1 ;;
	    i|I)	[ "$proceed" ] && MENU_DONE=true ;;
	    q|Q)	FINISH_SETUP=true; MENU_DONE=true ;;
	esac
    done
}

##############################################################################
# full check for permissions of files and directories
# only call this when being root
##############################################################################
do_check_permissions()
{
    clear
    echo "Checking permissions of $APS_BASEDIR"

    DIR_OWNER=`ls -lgd | "$AWK" '{ print $3 }'`
    DIR_GROUP=`ls -lgd | "$AWK" '{ print $4 }'`
    case $DIR_OWNER in
	root|daemon|bin|lp)
	    # ok, secure directory owner found
	    echo "found dir owner=$DIR_OWNER, ok!" ;;
	*)
	    # set secure directory owner
	    echo "found dir owner=$DIR_OWNER, not ok!"
	    echo "setting dir owner=bin!"
	    DIR_OWNER=bin ;;
    esac
    case $DIR_GROUP in
	root|wheel|other|bin|lp)
	    # ok, secure directory group found
	    echo "found dir group=$DIR_GROUP, ok!" ;;
	*)
	    # set secure directory group
	    echo "found dir group=$DIR_OWNER, not ok!"
	    echo "setting dir group=bin!"
	    DIR_GROUP=bin ;;
    esac

    # after having set sane defaults, fix permissions
    echo $n "changing permissions of $APS_BASEDIR... $c"
    chmod 555 .
    chown -R $DIR_OWNER:$DIR_GROUP .
    find . -type d -print | xargs chmod 555
    find . -type f -print | xargs chmod a+r,a-w
    echo "done."
    echo
    echo "Now we are checking file permissions in spooldir"

    set -- `ls -ld "$SPOOL"`
    LP_OWNER=$3; LP_GROUP=$4

    while [ ! "$PERM_OK" ]; do
	echo
	echo "Your line printer scheduler's spooldir seems to be: $SPOOL"
	echo
	ls -ld "$SPOOL"
	echo
	echo "The Owner of your spooldir seems to be: $LP_OWNER"
	echo "The Group of your spooldir seems to be: $LP_GROUP"
	echo
	echo $n "Is this correct? [y/n] $c"; read answer
	case $answer in
	    n|N)
		# ask the user
		echo $n "Path of Spool Dir? [default: $SPOOL] $c"
		read $read_r answer
		[ "$answer" ] && SPOOL="$answer"
		mkdir -p "$SPOOL"

		echo $n "Owner of Spool Dir? [default: $LP_OWNER] $c"
		read $read_r answer
		[ "$answer" ] && LP_OWNER="$answer"

		echo $n "Group of Spool Dir? [default: $LP_GROUP] $c"
		read $read_r answer
		[ "$answer" ] && LP_GROUP="$answer"
		;;
	    *)
		# o.k., do nothing
		PERM_OK=1
		;;
	esac
    done
}

##############################################################################
# Save printcap
#	- save the original printcap		-> printcap.orig
#	- make a work copy of the printcap file -> printcap.old
##############################################################################
do_save_printcaps()
{
    echo
    if [ -f "/etc/printcap" ]; then
	if [ ! -f "/etc/printcap.orig" ]; then
	    echo "saving original printcap -> /etc/printcap.orig"
	    cp "/etc/printcap" "/etc/printcap.orig"
	fi
	echo "creating a working copy of printcap -> /etc/printcap.old"
	cp "/etc/printcap" "/etc/printcap.old"
    else
	touch "/etc/printcap"
    fi
}

##############################################################################
# Was printcap already created by apsfilter?
# If so: keep entries or overwrite?
##############################################################################
do_check_for_old_apsfilter_installation()
{
    if [ -d "$CONF_DIR" ]; then
	if [ -d "$CONF_DIR/basedir" ]; then
	    OLD_BASEDIR=$(ls -l "$CONF_DIR/basedir" | sed 's/.*-> //')
	    if [ "$APS_BASEDIR" != "$OLD_BASEDIR" ]; then
		echo
		echo "WARNING! A previous installation of apsfilter is located"
		echo "in '$OLD_BASEDIR'."
		echo
		echo $n "Do you want to continue? $c"; read answer
		case $answer in
		    n|N)  exit 1 ;;
		esac
	    fi
	fi
	echo
	echo "It seems you have configured a printer with this script before."
	echo
	echo "Do you want to (a)dd another printer entry or"
	echo "            to (o)verwrite the existing entries?"
	echo $n "a/o? $c"; read answer
	
	case $answer in
	    o|O)
		echo "Ok, erasing old apsfilter entries..."
		sed -e "/# APS.*BEGIN/,/# APS.*END/ d" \
		    < "/etc/printcap.old" > "/etc/printcap"
		chmod 644 "/etc/printcap"
		;;
	    *)
		echo "Ok, adding another apsfilter printer..."
		;;
	esac
    fi
}

##############################################################################
# The real work:
#	- create printer configuration directory under $CONF_DIR
#	- install filter link in that directory
#	- create printer specific configuration file
##############################################################################

do_install_filter()
{
    clear

    #
    # Determine highest number of Apsfilter Printer in printcap
    #
    PRINTER_ENTRIES=`grep "APS.*_BEGIN" "/etc/printcap" | sort -n`
    PRINTER_ENTRIES=${PRINTER_ENTRIES##*printer}
    N=`expr ${PRINTER_ENTRIES:-0} + 1` 

    { # create printer start label
	echo "# APS${N}_BEGIN:printer$N"
	echo "# - don't delete start label for apsfilter printer$N"
	echo "# - no other printer defines between BEGIN and END LABEL"
    } >> "/etc/printcap"

    while :; do
	# set printer queue name; use "lp" if not already present
	if grep -E "^lp[|:]|^[^#].*\|lp[|:]" "/etc/printcap" >/dev/null; then
	    nr=1  # get a free "aps$nr" printer name
	    while grep -E "^aps${nr}[|:]|^[^#].*\|aps${nr}[|:]" "/etc/printcap" >/dev/null; do
		nr=`expr $nr + 1`
	    done
	    QUEUE="aps$nr"
	else
	    QUEUE=lp
	fi
	cat <<EOF

Please enter a printer queue name for printer '$PRINTER'.
The default name is '$QUEUE'.

EOF
	echo $n "Your choice: $c"; read $read_r answer
	[ "$answer" ] && QUEUE="$answer"

	if grep -E "^${QUEUE}[|:]|^[^#].*\|${QUEUE}[|:]" "/etc/printcap" >/dev/null
	then
	    echo
	    echo "I'm sorry, but '$QUEUE' is already in use."
	else
	    break
	fi
    done

    # create configuration directory for this printer and cd into it
    mkdir -p "$CONF_DIR/$QUEUE"
    cd "$CONF_DIR/$QUEUE"

    # printer name in printcap
    echo "** creating printcap entry for printer $QUEUE..."

    { # append following output to printcap

	echo "$QUEUE|$PRINTER;r=$RESOLUTION;q=$QUALITY;c=$COLOR;p=$PAPER;m=$METHOD:\\"

	# interface configuration
	case $INTERFACE in
	    parallel)
		echo "    :lp=$DEVICE:\\"
		;;
	    serial)
		echo "    :lp=$DEVICE:\\"
		echo "    :br#$BAUD:\\"
		echo "    :ms=ixon,-imaxbel,-ixany,-ixoff,-crtscts:\\"
		;;
	    network)
		echo "    :lp=:\\"
		echo "    :rm=$rm:\\"
		echo "    :rp=$rp:\\"
		;;
	    samba|atalk|netware)
		echo "    :lp=/dev/null:\\"
		;;
	esac

	# filter and spooldir configuration in printcap
	echo "    :if=$CONF_DIR/basedir/bin/apsfilter:\\"
	SPOOLDIR="$SPOOL/$QUEUE"
	echo "    :sd=$SPOOLDIR:\\"

	# logfile configuration in printcap
	echo "    :lf=$SPOOLDIR/log:\\"

	# accounting file configuration in printcap
	echo "    :af=$SPOOLDIR/acct:\\"

	# no size limitation for printjob in printcap
	echo "    :mx#0:\\"

	# suppress formfeed when printing raw
	[ "$METHOD" = raw ] && echo "    :sf:\\"

	# last entry, suppress printing of burst page
	echo "    :sh:"

	# create printer end label
	echo "# APS${N}_END - don't delete this"
    } >> "/etc/printcap"

    # create spooldir in Unix filesystem
    echo "   creating spooldir ..."
    mkdir -m 755 -p "$SPOOLDIR"
    # maybe chmod knows "--reference" to clone the permissions
    chmod --reference="$SPOOL" "$SPOOLDIR" 2>/dev/null

    # create needed empty files under Spooldir
    : > "$SPOOLDIR/log"
    : > "$SPOOLDIR/acct"

    # that's needed specially for Linux Slackware
    : > "$SPOOLDIR/lock"
    chmod 664 "$SPOOLDIR/lock"

    # set sane permissions for spooldir
    [ `id -u` -eq 0 ] && chown -R $LP_OWNER:$LP_GROUP "$SPOOLDIR"

    if [ "$INTERFACE" = samba ]; then
	echo "   creating samba config file ..."

	{ # write all output to smbclient.conf

	    echo "SMB_SERVER='$SMB_SERVER'"
	    echo "SMB_IP='$SMB_IP'"
	    echo "SMB_PRINTER='$SMB_PRINTER'"
	    echo "SMB_WORKGROUP='$SMB_WORKGROUP'"
	    echo "SMB_BUFFER=1400"
	    echo "SMB_FLAGS='-N'"

	    # print on remote windows machine as real user...
	    if [ "$SMB_USER" ]; then
		echo "SMB_USER='$SMB_USER'"
		echo "SMB_PASSWD='$(echo $SMB_PASSWD | sed "s/'/'\\\''/g")'"
	    fi

	} > smbclient.conf

	# protect smbclient file, if it contains password information
	if [ "$SMB_PASSWD" ]; then
	    echo "   read protect password information..."
	    chmod 600 smbclient.conf
	    chown $LP_OWNER:$LP_GROUP smbclient.conf
	fi
    elif [ "$INTERFACE" = atalk ]; then
	echo "   creating AppleTalk config file ..."
	echo "PAP_NBPNAME='$PAP_NBPNAME'" > pap.conf
    elif [ "$INTERFACE" = netware ]; then
	echo "   creating NetWare config file ..."
	{
	    echo "NCP_SERVER='$NCP_SERVER'"
	    echo "NCP_PRINTER='$NCP_PRINTER'"
	    echo "NCP_USER='$NCP_USER'"
	    echo "NCP_PASSWD='$(echo $NCP_PASSWD | sed "s/'/'\\\''/g")'"
	} > netware.conf

	# protect netware file if it contains password information
	if [ "$NCP_PASSWD" ]; then
	    echo "   read protect password information..."
	    chmod 600 netware.conf
	    chown $LP_OWNER:$LP_GROUP netware.conf
	fi
    fi

    # Save some settings from this SETUP session
    echo "   remember SETUP settings in printers apsfilterrc file..."

    {
	echo "#"
	echo "# don't delete these settings"
	echo "#"
	echo "PRINTER='$PRINTER'"
	echo "PAPERSIZE='$PAPER'"
	echo "METHOD='$METHOD'"
	echo "QUALITY='$QUALITY'"
	echo "COLOR='$COLOR'"
	echo "RESOLUTION='$RESOLUTION'"
	echo
	echo "#"
	echo "# additional configuration follows"
	echo "# insert settings as seen in $CONF_DIR/apsfilterrc"
	echo "#"
	[ "$PS_INIT" ] && echo "PS_INIT='$PS_INIT'"
    } > apsfilterrc

    # in case LPRng is used: checkpc does a nice cleanup
    type checkpc > /dev/null 2>&1 && checkpc -f >/dev/null 2>&1

    echo "** done."
    echo
    echo $n "[ press <RETURN> to continue ] $c"; read answer
    cd "$APS_BASEDIR"
}


#
# print error message and quit
#
fail()
{
    echo >&2 "SETUP error: $@"
    exit 1
}

#####################################################
#####################################################
#####################################################
####                                             ####
####                 M A I N                     ####
####                                             ####
#####################################################
#####################################################
#####################################################

export APS_BASEDIR="/usr/local/share/apsfilter"
cd "$APS_BASEDIR"
CONF_DIR="/usr/local/etc/apsfilter"
SPOOL="/var/spool/lpd"

# check read/write permissions
[ -w . ] || fail "no write access to $APS_BASEDIR"
if [ -d "$CONF_DIR" ]; then
    [ -w "$CONF_DIR" ] || fail "no write access to $CONF_DIR"
elif [ -d "/usr/local/etc" ]; then
    [ -w "/usr/local/etc" ] || fail "no write access to /usr/local/etc"
else
    mkdir -p "/usr/local/etc" || fail "couldn't create /usr/local/etc"
fi
if [ -f "/etc/printcap" ]; then
    [ -r "/etc/printcap" -a -w "/etc/printcap" ] || fail "no r/w access to /etc/printcap"
fi
printcap_dir=`dirname "/etc/printcap"`
if [ -d "$printcap_dir" ]; then
    [ -w "$printcap_dir" ] || fail "no write access to $printcap_dir"
else
    mkdir -p "$printcap_dir" || fail "couldn't create $printcap_dir"
fi
if [ -d "$SPOOL" ]; then
    [ -w "$SPOOL" ] || fail "no write access to $SPOOL"
else
    mkdir -p "$SPOOL" || fail "couldn't create $SPOOL"
    [ `id -u` -eq 0 ] && { chown lp "$SPOOL" || chown daemon "$SPOOL"; }
fi


# check if we must use the "-r" flag for "read" operations
if echo dummy | read -r dummy 2>/dev/null; then
    read_r="-r"
else
    unset read_r
fi

# how to suppress newlines on echo
if echo "\c" | grep -c . >/dev/null; then
    n='-n'; c=''
else
    n=''; c='\c'
fi

do_check_gs_version
do_copyright

# some people got nerved, me too ;-)
if [ -f .requested_snailmail ]; then
    echo "You already requested my snailmail address to write a postcard"
    echo $n "Request it again? [y/n] $c"; read answer
    case $answer in
	y|Y|j|J)    do_request_snailmail ;;
    esac
else
    do_request_snailmail
fi

do_start

# provide some (more or less) sane default values
PRINTER=
PAPER=
INTERFACE=
DEVICE=
QUALITY=medium
COLOR=full
RESOLUTION=300x300
METHOD=auto

# read old settings from SETUP.cfg if present
[ -f SETUP.cfg ] && . ./SETUP.cfg

# do a full check when being root
[ `id -u` -eq 0 ] && do_check_permissions

# prepare filter installation
clear
do_save_printcaps
do_check_for_old_apsfilter_installation

# Create - an apsfilter directory under /etc (if not already present)
#        - a link $CONF_DIR/basedir -> APS_BASEDIR
#        - a global configuration file (if not already present)
mkdir -p -m 755 "$CONF_DIR"
rm -f "$CONF_DIR/basedir"
ln -s "$APS_BASEDIR" "$CONF_DIR/basedir"
[ -f "$CONF_DIR/apsfilterrc" ] || cp template/apsfilterrc "$CONF_DIR"


#
# Main loop
#
do_main_menue
while [ -z "$FINISH_SETUP" ]; do
    do_install_filter
    do_main_menue
done


##############################################################################
# End of creating
# - printcap entries
# - filesystem operations (spooldir, symlink, ... -creation)
##############################################################################

##############################################################################
#
# now proceed with installation, save environment

do_save_environment

clear
cat <<EOF

Finished creating/updating /etc/printcap and $CONF_DIR/ ...


To let the printer scheduler know of the new printers, it has to be
restarted. Be sure that no print jobs are in the queue.

For LPRng use:  lpc reread
For *BSD  use:  lpc restart all

For Linux BSD-lpr use the vendor supplied script, i.e.:
    /etc/rc.d/init.d/lpd restart
or similar.


Now some important news/information follow...

Please read them carefully!

[ press <RETURN> to continue ]
EOF
read answer

clear
cat << !EOM
    _/      _/
   _/_/    _/   _/_/   _/      _/      _/   _/_/_/
  _/  _/  _/ _/_/_/_/ _/      _/      _/ _/_/
 _/    _/_/ _/         _/  _/  _/  _/       _/_/
_/      _/   _/_/_/     _/      _/     _/_/_/

	See the ANNOUNCE and ChangeLog files for more informations.
	New: read the manual pages apsfilter(1) and apsfilterrc(5)

	New CLASS support (lpr -C) allows you to set one ore more options
	for gs (PS Emulator), separated by colons (":").

	CLASS support is currently available for some gs drivers. Look into
	apsfilter script, which driver dependent options are supported.

	Example: stcolor print driver: set 
		- print resolution to high resolution (720dpi)
		- color depth to 30 bits per pixel

	  lpr -C high:30bpp file1..fileN

!EOM
echo $n "[ press <RETURN> to continue ]$c"; read answer

clear
cat << !EOM
    _/      _/
   _/_/    _/   _/_/   _/      _/      _/   _/_/_/
  _/  _/  _/ _/_/_/_/ _/      _/      _/ _/_/
 _/    _/_/ _/         _/  _/  _/  _/       _/_/
_/      _/   _/_/_/     _/      _/     _/_/_/

	New: apsfilterrc config files per single printer!
	New: name and location change in apsfilterrc config files!
	New: manual page for apsfilter(1) and apsfilterrc(5) config files!

	A) global apsfilter config file, set by admin
		$CONF_DIR/apsfilterrc

	B) printer specific config file for printer N, set by admin
		$CONF_DIR/QUEUE/apsfilterrc

	C) user supplied config options on per printer basis, set by admin
		$CONF_DIR/QUEUE/apsfilterrc.USER

	D) user controllable config file on per printer basis;
	   *SECURITY*HOLE*, needs USE_USER_CODE set in A), B) or C)
		$HOME/.apsfilter/apsfilterrc.QUEUE

!EOM
echo $n "[ press <RETURN> to continue ]$c"; read answer

clear
cat << !EOM
    _/      _/
   _/_/    _/   _/_/   _/      _/      _/   _/_/_/
  _/  _/  _/ _/_/_/_/ _/      _/      _/ _/_/
 _/    _/_/ _/         _/  _/  _/  _/       _/_/
_/      _/   _/_/_/     _/      _/     _/_/_/

	For printing ASCII files apsfilter now uses a2ps V. 4.12 or higher.
	Old patched a2ps and rewindstdin have gone!

	You can also use mpage or recode; see apsfilterrc for this setting.

	remote printing is fully supported by apsfilter:
	- on Unix remote printer (lpd) and
	- Windows 95/98/NT/2000 Remote Printer

!EOM
echo $n "[ press <RETURN> to continue ]$c"; read answer

clear
cat << !EOM
                                                _/
   _/  _/_/   _/_/   _/_/_/  _/_/     _/_/   _/_/_/_/   _/_/
  _/_/     _/_/_/_/ _/    _/    _/ _/    _/   _/     _/_/_/_/
 _/       _/       _/    _/    _/ _/    _/   _/     _/
_/         _/_/_/ _/    _/    _/   _/_/       _/_/   _/_/_/ _/ _/ _/

You need SAMBAs smbclient utility, to print on Windows remote printer.
SETUP makes the necessary entries in printcap(5).

You need a line printer scheduler (fixed lpd or LPRng) on your system
that allows to use input filters (printcap: if=...) when printing
to remote printers (printcap: rm:..., rp:...)

FreeBSD 3.x and later have a fixed lpd, no problem here.

Otherwise use the lpd successor LPRng (lineprinter next generation)
or configure lpr.conf in the lineprinters spool directory (new!)

!EOM
echo $n "[ press <RETURN> to continue ]$c"; read answer

clear
cat << !EOM
    _/_/_/                     _/
   _/    _/   _/_/     _/_/_/      _/_/_/ _/_/_/
  _/    _/ _/_/_/_/ _/_/     _/ _/    _/ _/    _/
 _/    _/ _/           _/_/ _/ _/    _/ _/    _/
_/_/_/     _/_/_/ _/_/_/   _/   _/_/_/ _/    _/ _/ _/ _/
                                   _/
                              _/_/

Apsfilter can be installed on a Server or Desktop machine. Best is to install
it on a dedicated Server, where printers are locally connected to, since
ghostscript Postscript emulation might become a CPU intensive process. The
faster the CPU, the faster the Postscript emulation and printing in general.

If you want to print on Network printer using the lpd protocol, you should
install apsfilter on a machine which has a fixed lineprinter scheduler and
is able to use input filters (apsfilter) when printing to a remote printer.
FreeBSD 3.x and later has a fixed lpd, otherwise use the lpd successor LPRng.

Since apsfilter 5.2.0 you can also print to Windows remote printers, that
are printers on Windows machines, which are shared in the network. You need
to install SAMBA on the Unix apsfilter hosts, who want to use Windows printers.

!EOM
echo $n "[ press <RETURN> to continue ]$c"; read answer

clear
cat << !EOM
    _/_/_/
   _/    _/ _/  _/_/   _/_/   _/_/_/  _/_/     _/_/
  _/_/_/   _/_/     _/    _/ _/    _/    _/ _/    _/
 _/       _/       _/    _/ _/    _/    _/ _/    _/
_/       _/         _/_/   _/    _/    _/   _/_/   _/ _/ _/

I'd really like to get some mails from you, 
	- why you like apsfilter
	- how apsfilter saved your or your companies printing problems

Please send apsfilter promotion e-mails to the following e-mail address:
	apsfilter-promo@apsfilter.org

In return you get the possibility to introduce you and your company
and how apsfilter solved your or your companies printing problems ;-)

!EOM
echo $n "[ press <RETURN> to continue ]$c"; read answer

clear
cat << !EOM
     _/_/_/  _/  _/    _/_/_/    _/    _/
  _/        _/  _/    _/    _/      _/_/_/_/    _/_/_/
 _/_/_/    _/_/_/_/  _/_/_/    _/    _/      _/_/
_/    _/      _/    _/    _/  _/    _/          _/_/
 _/_/        _/    _/_/_/    _/      _/_/  _/_/_/

Our band "64Bits":
Please visit our band's homepage, from there you get band
informations and you can download cool songs.

Official band pages:
	http://www.64bits.de/

Inofficial band pages:
	http://www.apsfilter.org/64bits.html

Please send us e-mail, how you find the song, etc.
Since we only have few time to probe because of job (you know ;-)
we currently are unable to make live concerts.

So YOU are our virtual audience and we'd LOVE to get some feedback ;-)
Thanks!

!EOM
echo $n "[ press <RETURN> to continue ]$c"
read answer

#
# This for the last screen with most important infos...
#
clear
cat << !EOM

============================
Apsfilter Internet Resources
============================

Apsfilter's homepage (News, Updates, Patches, ...):

	http://www.apsfilter.org/

Read the ANNOUNCE file about Apsfilter Internet Resources
and how to use them:

	- Apsfilter developement machine
	- Apsfilter mailing lists
	- Apsfilter CVS repository
	- Apsfilter Anonymous CVS server
	- Apsfilter CVS repository browser (cvsweb, enhanced Zeller version)

Please report questions and bugs to the offical apsfilter help channel:

	apsfilter-help@apsfilter.org

*** SETUP done ***
!EOM

exit 0
