#! /bin/sh
# -*- sh -*-

#
# $ApsCVS: src/apsfilter/SETUP,v 1.112.2.6 2001/03/29 20:01:41 andreas Exp $
#
# apsfilter setup tool
#
# written by Andreas Klemm <andreas@apsfilter.org>
# modified for V6.0 by Michael Loin <losse@germanymail.com>
#

#
# 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"
VERSION=6.1.1
: ${TMPDIR:=/tmp}
export PATH TMPDIR

#
# 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  request-snailmail@klemm.gtn.com  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 MTA...
	    while [ -z "$SENDMAIL_OK" ]; do
		if [ -x /usr/lib/sendmail ]; then
		    SENDMAIL=/usr/lib/sendmail
		    echo "Good, sendmail is $SENDMAIL..."
		    sleep 2
		    SENDMAIL_OK=true
		elif [ -x /usr/sbin/sendmail ]; then
		    SENDMAIL=/usr/sbin/sendmail
		    echo "Good, sendmail is $SENDMAIL..."
		    sleep 2
		    SENDMAIL_OK=true
		else
		    cat << !EOM
*** Oops, was looking for sendmail in /usr/sbin and /usr/lib, but your ***
*** mail transport agent (MTA) seems to live in an unusual place ...   ***
*** Please type in the complete path to your MTA, which is on most     ***
*** Unix machines sendmail, but could also be postfix, qmail or smail  ***
*** i.e.: /usr/somepath/sendmail                                       ***
!EOM
		    echo $n ": $c"; read $read_r SENDMAIL
		    echo
		    if [ -x "$SENDMAIL" ]; then
			echo "Using $SENDMAIL as MTA..."
			sleep 2
			SENDMAIL_OK=true
		    fi
		fi
	    done

	    echo
	    # 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: request-snailmail@klemm.gtn.com"
		echo "Reply-To: $REPLYTO"
		echo "Subject: get snailmail for apsfilter version $VERSION"
	    } | "$SENDMAIL" request-snailmail@klemm.gtn.com
	    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 $VERSION
			*** The Unix Print Solution ***
        ================================================================

                       copyright Andreas Klemm, 1993-2001

                              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 /etc/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 /etc/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
	6.[5-9]*)
	    GS_BASE=6.50 ;;
	6*)
	    GS_BASE=6.01 ;;
	*)
	    GS_BASE=5.50

	    cat <<EOF
Found ghostscript version $GS_VERSION ...
You have to upgrade at least to gs version 5.50!
But you should upgrade to gs 6.01 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
    2) printer driver natively supported by ghostscript

    3) gimp-print / stp
    4) hpdj
    5) pcl3 (successor to hpdj, experimental)
    6) IBM Omni
    7) cdj880, cdj970
    8) PPA printer, needs ghostscript "ppmraw" device and pnm2ppa

    0) return to main menu

!EOM
    echo $n "Your choice: $c"; read answer
    case $answer in
	1)	PRINTER_LIST=setup/printer-ps ;;
	2)	PRINTER_LIST=setup/printer-$GS_BASE ;;
	3)	PRINTER_LIST=setup/printer-stp ;;
	4)	PRINTER_LIST=setup/printer-hpdj ;;
	5)	PRINTER_LIST=setup/printer-pcl3 ;;
	6)	PRINTER_LIST=setup/printer-omni ;;
	7)	PRINTER_LIST=setup/printer-cdj ;;
	8)	PRINTER_LIST=setup/printer-ppa ;;
	*)	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
		PS_*)	;;
		PSgs_*)	check_for_gs_support pswrite && \
			check_for_gs_support psgray ;;
		ppa_*)	check_for_gs_support ppmraw ;;
		*.upp)	check_for_gs_support uniprint ;;
		stp_*)	check_for_gs_support stp ;;
		omni_*)	check_for_gs_support omni ;;
		hpdj*)	check_for_gs_support hpdj ;;
		pcl3*)	check_for_gs_support pcl3 ;;
		*)	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

    # After this step has been successfully performed we fill the main menue
    # field "printer driver resolution" with the string default, indicating
    # that the driver's default resolution is active unless you change it.

    case "$PRINTER" in
	PSgs_*dpi)	RESOL="${PRINTER#PSgs_}"; RESOL="${RESOL%dpi}" ;;
	*)		RESOL=default ;;
    esac
    COLOR=default
    # BPP is later used for the bpp value in symlinks
    BPP=$COLOR
}

check_for_gs_support()
{
    # check for gs
    type gs >/dev/null 2>&1 || warn_about_missing_gs

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

Error: Your gs version doesn't have driver "$1" 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=""
    fi
}

##############################################################################
# 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
	Linux:                      LPT1: /dev/lp0    LPT2: /dev/lp1
		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"
}

##############################################################################
# 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 printers spool 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 (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
}

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

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, odd or mark 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

!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 ;;
	*)  INTERFACE=parallel; do_ask_parallel_device ;;
    esac
}

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

	New: this setup affects the print resoulution for the printer
	installation and printing of the "Test Page"

	You should always start with the drivers default resolution.

	Hint: for some Laser Printers (i.e. HP LaserJet II) you have
	to choose a smaller print resolution than the drivers default
	resolution, because of a lack of memory!

	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

	d) back to default resolution of the printer driver

!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 ;;
	c|C) # custom settings
	    echo $n "Please input x-resolution in dpi: $c"; read XRESOL
	    echo $n "Please input y-resolution in dpi: $c"; read YRESOL
	    ;;
	d|D)
	    XRESOL=""; YRESOL=""; RESOL=default
	    ;;
    esac

    # XXX this fix was not 100% o.k.
    # right to fix display of resol after changing again to default
    # (GS_RESOL=x bug)
    # but now you aren't able choose a different resolutions than default...
    # has to be re-thought
    #   if [ "$RESOL" != "default" ]; then
    #	    RESOL="${XRESOL}x${YRESOL}"
    #   fi
    # So re-enable working code...
    # RESOL="${XRESOL}x${YRESOL}"
    if [ "$XRESOL" != "" -a "$YRESOL" != "" ]; then
	RESOL="${XRESOL}x${YRESOL}"
    fi
}

##############################################################################
# Toggle between color and monochrome mode for test page
##############################################################################
do_toggle_color()
{
    clear
    cat << !EOM
        ----------------------------------------------------------------
        A P S F I L T E R   S E T U P             -- Mono/Color Setup --
        ----------------------------------------------------------------

	If your printer/driver support color output, then the driver
	has certain defaults compiled in.

	Some of the drivers support printing in high quality color mode.
	The number of "bits per pixel" (bpp) determine the number of
	colors and so the quality of color prints.

	This is kind of "expert mode", because you have to know, what
	your printer and the ghostscript printer driver support !
	If you have no better idea, then please choose "default".

	d)	default (highly recommended!)

	m)	monochrome (1 bpp)
						4)	16 bpp  (color)
	1)	3 bpp   (color)			5)	24 bpp  (color)
	2)	4 bpp   (color)			6)	30 bpp  (color)
	3)	8 bpp   (color)			7)	32 bpp  (color)

!EOM
    echo $n "Your choice? $c"; read answer
    case $answer in
	1)  COLOR=3;       BPP=$COLOR ;;
	2)  COLOR=4;       BPP=$COLOR ;;
	3)  COLOR=8;       BPP=$COLOR ;;
	4)  COLOR=16;      BPP=$COLOR ;;
	5)  COLOR=24;      BPP=$COLOR ;;
	6)  COLOR=30;      BPP=$COLOR ;;
	7)  COLOR=32;      BPP=$COLOR ;;
	m)  COLOR=1;       BPP=$COLOR ;;
	d)  COLOR=default; BPP=$COLOR ;;
    esac
}

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
	2) DIN A3
	3) US letter
	4) US legal
	5) US ledger

!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=ledger ;;
    esac
}

do_print_test_page()
{
    if [ -n "$RESOL" -a "$RESOL" != "default" ]; then
	RESOLUTION="-r$RESOL"
    else
	RESOLUTION=""
    fi

    if [ -n "$BPP" -a "$BPP" != "default" ]; then
	BITSPERPIXEL="-dBitsPerPixel=$BPP"
    else
	BITSPERPIXEL=""
    fi

    # hpdj and pcl3 drivers don't allow finetuning of BPP value
    case $PRINTER in
	hpdj*|pcl3*)	BITSPERPIXEL="" ;;
    esac

    # 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=$(mktemp 2>/dev/null $TMPDIR/aps_testout.XXXXXX \
	    || echo $TMPDIR/aps_testout.$$)

    # 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
	PS_*dpi)
	    # real PS printer
	    CREATE_TESTPAGE_CMD="cat setup/test.ps > '$TESTOUT'"
	    ;;
	PSgs_*dpi)
	    # PS printer, driven by ghostscript "pswrite"
	    CREATE_TESTPAGE_CMD="cat setup/test.ps | gs -q $RESOLUTION \
		-sDEVICE=pswrite -sPAPERSIZE=$PAPER -dNOPAUSE -dSAFER \
		-sOutputFile='$TESTOUT' -"
	    ;;
	*.upp)
	    # uniprint driver
	    CREATE_TESTPAGE_CMD="cat setup/test.ps | gs -q @$PRINTER \
		-sPAPERSIZE=$PAPER -sOutputFile='$TESTOUT' -"
	    ;;
	hpdj|hpdj_u970|pcl3|pcl3_u970)
	    # hpdj/pcl3 drivers, "unspec" model
	    CREATE_TESTPAGE_CMD="cat setup/test.ps | gs -q $RESOLUTION \
		-sDEVICE=${PRINTER%%_*} -sModel=unspec \
		-sPAPERSIZE=$PAPER -dNOPAUSE -dSAFER \
		-sOutputFile='$TESTOUT' $PS_INIT -"
	    ;;
	hpdj_*|pcl3_*|stp_*)
	    # hpdj, pcl3 and stp drivers
	    CREATE_TESTPAGE_CMD="cat setup/test.ps | gs -q $RESOLUTION \
		-sDEVICE=${PRINTER%%_*} -sModel=${PRINTER#*_} \
		-sPAPERSIZE=$PAPER -dNOPAUSE -dSAFER \
		-sOutputFile='$TESTOUT' $PS_INIT -"
	    ;;
	omni_*)
	    # IBM omni driver
	    CREATE_TESTPAGE_CMD="cat setup/test.ps | gs -q $RESOLUTION \
		-sDEVICE=omni -sDeviceName=${PRINTER#omni_} \
		-sform=FORM_$(echo $PAPER | tr a-z A-Z) \
		-sPAPERSIZE=$PAPER -dNOPAUSE -dSAFER \
		-sOutputFile='$TESTOUT' $PS_INIT -"
	    ;;
	ppa_*)
	    # ppa printers (some HP deskjet models)
	    CREATE_TESTPAGE_CMD="cat setup/test.ps | gs -q -r600 \
		-sDEVICE=ppmraw -sPAPERSIZE=$PAPER -dNOPAUSE -dSAFER \
		-sOutputFile=- - | pnm2ppa -v ${PRINTER#ppa_} -o '$TESTOUT'"
	    ;;
	*)
	    CREATE_TESTPAGE_CMD="cat setup/test.ps | gs -q $RESOLUTION \
		$BITSPERPIXEL -sDEVICE=$PRINTER -sPAPERSIZE=$PAPER \
		-dNOPAUSE -dSAFER -sOutputFile='$TESTOUT' $PS_INIT -"
	    ;;
    esac

    # Tell the magic command ...
    echo
    echo $n "Printing Test page using: $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 $RESOL $BPP" >> 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="cat '$TESTOUT' | smbclient \
			//${SMB_SERVER}/${SMB_PRINTER} ${SMB_IP:+-I $SMB_IP} \
			${SMB_LOGIN} ${SMB_WORKGROUP:+-W} ${SMB_WORKGROUP} \
			-b 1400	-N -c 'print -'"
		elif [ "$INTERFACE" = atalk ]; then
		    PRINT_TESTP_CMD="cat '$TESTOUT' | pap -e -p '$PAP_NBPNAME'"
		else
		    PRINT_TESTP_CMD="cat '$TESTOUT' > $DEVICE"
		fi

		ls -l "$TESTOUT" | tee -a perf.log
		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 test file
    rm -f "$TESTOUT"
}

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 resolution,
	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 last some time, please be patient.

	T)  Print a test page on local/samba/appletalk printer
	*)  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'
XRESOL='$XRESOL'
YRESOL='$YRESOL'
RESOL='$RESOL'
RESOLUTION='$RESOLUTION'
BITSPERPIXEL='$BITSPERPIXEL'
COLOR='$COLOR'
PAPER='$PAPER'
BPP='$BPP'
INTERFACE='$INTERFACE'
DEVICE='$DEVICE'
BAUDRATE='$BAUDRATE'
HANDSHAKE='$HANDSHAKE'
WORDLENGTH='$WORDLENGTH'
PARITY='$PARITY'
STARTBITS='$STARTBITS'
STOPBITS='$STOPBITS'
DISPLAY_RESOL='$DISPLAY_RESOL'
DISPLAY_BPP='$DISPLAY_BPP'
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")'
EOF
    if [ "$SMB_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
	# nicer display of print resolution...
	case $RESOL in
	    ""|default)	DISPLAY_RESOL=$RESOL ;;
	    *)		DISPLAY_RESOL="${RESOL}dpi" ;;
	esac

	# nice display of monochrome and color printing
	case $COLOR in
	    ""|default)	DISPLAY_BPP=$COLOR ;;
	    *)		DISPLAY_BPP="${COLOR}bpp" ;;
	esac

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

                                                        currently selected
        ------------------------------------------------------------------
	(D)	Available Device Drivers in your gs binary
	(R)	Read Ghostscript driver documentation        (devices.txt)
	(1)	Printer Driver Selection                     [$PRINTER]
	(2)	Interface Setup                              [$INTERFACE]

	For printing the test page:
	(3)	Paper Format (mandatory)		[$PAPER]
!EOM
	case $PRINTER in
	    *.upp|PS*dpi)	echo $n "	$c" ;;
	    *)			echo $n "	(4)$c" ;;
	esac
	echo "	Print Resolution in \"dots per inch\"	[$DISPLAY_RESOL]"

	case $PRINTER in
	    hpdj*|pcl3*|stp_*|ppa_*|omni_*)	echo $n "	$c" ;;
	    *)					echo $n "	(5)$c" ;;
	esac
	echo "	Toggle Monochrome/Color (1bpp=b&w)	[$DISPLAY_BPP]"

	cat << !EOM
	(T)	Print Test Page, on local or Windows remote prt.(after 1-5)
	(V)	View perf.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
	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)		case $PRINTER in
			    *.upp|PS*dpi)	;;
			    *)			do_choose_resolution ;;
			esac ;;
	    5)		case PRINTER in
			    hpdj*|pcl3*|stp_*|ppa_*|omni_*)	;;
			    *)			do_toggle_color ;;
			esac ;;
	    t|T)	do_print_test_menue ;;
	    v|V)	do_view_perflog ;;
	    a|A)	exit 1 ;;
	    i|I)	MENU_DONE=true ;;
	    q|Q)	FINISH_SETUP=true; MENU_DONE=true ;;
	esac
    done
}

##############################################################################
# Get the configuration directory
# (formerly this was fixed to /etc/apsfilter)
##############################################################################

do_get_conf_dir()
{
    clear
    : ${CONF_DIR:=/etc/apsfilter}

    cat <<EOF
	    ==========================================
		Setting up configuration directory
	    ==========================================

	Please enter the path of the directory you want to keep the
	printer configuration files in. This directory will be created
	if it doesn't already exist.

	Common locations are:

	    /etc/apsfilter			/usr/etc/apsfilter
	    /usr/local/etc/apsfilter		/opt/etc/apsfilter
	    /usr/pkg/apsfilter/etc		/opt/local/apsfilter/etc

	and so on.

	You might run into trouble if you enter the apsfilter
	installation directory here (but an "etc" subdirectory is okay).

	Default: $CONF_DIR

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

##############################################################################
# - usually the apsfilter script is being executed with certain system
#   privileges during runtime
# - so we have to make sure, that ordinary users aren't allowed to modify
#   the scripts
# - fix things if user allows it, otherwise exit ...
# - also check the spool directory
##############################################################################
do_check_permissions()
{
    clear
    case `uname -n` in
	*klemm.gtn.com)
	    # don't check permissions on my system
	    ;;
	*)
	    # fix permissions on a production machine 
	    FIX_PERMISSIONS=true ;;
    esac

    #
    # on a production machine always fix permissions!
    #
    if [ "$FIX_PERMISSIONS" ]; then
	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."
    fi

    echo
    echo
    echo "Now we are checking file permissions in spooldir"

    if [ -d /var/spool/lpd ]; then
	SPOOL=/var/spool/lpd
    elif [ -d /var/spool ]; then
	SPOOL=/var/spool
    else
	SPOOL=/var/spool/lpd
	mkdir -p $SPOOL
	chown lp $SPOOL || chown daemon $SPOOL
    fi
    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 /etc/printcap
#	- save the original printcap		-> /etc/printcap.orig
#	- make a work copy of the printcap file -> /etc/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
}

##############################################################################
# install apsfilter.1 and apsfilterrc.5 (with optional compression)
##############################################################################
do_install_manpages()
{
    clear
    cat <<EOF
Manual Page Installation
========================

Please choose toplevel directory for manpage installation:

(1)	/usr/man
(2)	/usr/share/man
(3)	/usr/local/man
(4)	/usr/local/share/man
(0)     don't install man pages, i.e. FreeBSD ports collection (default)

EOF
    echo $n "Your selection? $c"; read answer

    case $answer in
	1) MANDEST=/usr/man ;;
	2) MANDEST=/usr/share/man ;;
	3) MANDEST=/usr/local/man ;;
	4) MANDEST=/usr/local/share/man ;;
	*) return ;;
    esac

    mkdir -p $MANDEST/man1 $MANDEST/man5

    cp man/apsfilter.1 $MANDEST/man1
    cp man/apsfilterrc.5 $MANDEST/man5

    cat <<EOF

Compress manual pages?

(1) using compress
(2) using gzip
(3) no compression

EOF
    echo $n "Your selection? $c"; read answer

    case $answer in
	1)  compress -f $MANDEST/man1/apsfilter.1 $MANDEST/man5/apsfilter.5 ;;
	2)  gzip -9f $MANDEST/man1/apsfilter.1 $MANDEST/man5/apsfilterrc.5 ;;
    esac
}

##############################################################################
# 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
    cat <<EOF
    ======================================================================
		    Filter installation -- final steps
    ======================================================================

It's recommended to have one 'raw' entry for each physical printer.
If you're not sure, say 'y' -- it won't hurt.

EOF
    echo $n "Do you want me to create one for printer at $DEVICE? (y/n) $c"
    read answer
    case $answer in
	n|N)	METHOD=auto ;;
	*)	METHOD="auto raw" ;;
    esac
    echo

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

    for m in $METHOD; do
	while :; do
	    # set printer queue name; use "lp" if not already present
	    if grep -E "^lp[|:]|^[^#].*\|lp[|:]" /etc/printcap >/dev/null; then
		QUEUE="$m$N"
	    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 /etc/printcap

	    echo "$QUEUE|Printer$N $m:\\"

	    # 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)
		    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
	    [ "$m" = raw ] && echo "    :sf:\\"

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

	} >> /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
	chown -R $LP_OWNER.$LP_GROUP "$SPOOLDIR"

	# samba printer
	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
	fi

	# AppleTalk printer
	if [ "$INTERFACE" = atalk ]; then
	    echo "   creating AppleTalk config file ..."
	    echo "PAP_NBPNAME='$PAP_NBPNAME'" > pap.conf
	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='$m'"
	    echo "RESOLUTION='$RESOL'"
	    echo
	    echo "#"
	    echo "# additional configuration follows"
	    echo "# insert settings as seen in $CONF_DIR/apsfilterrc"
	    echo "#"
	    if [ -n "$BPP" -a "$BPP" != default ]; then
		BITSPERPIXEL="-dBitsPerPixel=$BPP"
		echo "GS_FEATURES='$BITSPERPIXEL'"
	    fi
	    [ "$RESOL" = default ] || echo "GS_RESOL='$RESOL'"
	    [ "$PS_INIT" ] && echo "PS_INIT='$PS_INIT'"
	} > apsfilterrc
    done

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

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

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

case `uname -n` in
    *klemm.gtn.com)
	# on my developement platforms don't check for root permissions ;-)
	;;
    *)	# only continue with root privileges since normal users are unable to
	# - change /etc/printcap
	# - write to the printer device
	# - setup spool directories as needed
	if [ `id -u` -ne 0 ]; then
	    echo "SETUP: error: must be root to install apsfilter"
	    exit 1
	fi
	;;
esac

# get the apsfilter installation directory
cd `dirname $0`; export APS_BASEDIR=`pwd`

# 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

# On Free-, Open-, NetBSD systems we have a ports collection
# Some setup steps don't have to be performed there
case `uname -s` in
    *FreeBSD*|*NetBSD*|*OpenBSD*)
	# Binary Compatibility I hope
	PORTS_COLLECTION=True
	;;
esac

do_start

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

# prepare filter installation
do_get_conf_dir
do_check_permissions
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, install manpages

do_save_environment

do_install_manpages

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@klemm.gtn.com

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.

Currently there is a Rock ballade available for download as
MPEG 3 file, please see:
	http://people.FreeBSD.org/~andreas/64bits/

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
