#!/bin/sh
#
# lpd           This shell script takes care of starting and stopping \
#               lpd (printer daemon).
#
# chkconfig: 2345 60 60
# description: lpd is the print daemon required for lpr to work properly. \
#       It is basically a server that arbitrates print jobs to printer(s).
# processname: /usr/sbin/lpd
# config: /etc/printcap

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration and check that networking is up.
if [ -f /etc/sysconfig/network ] ; then
	. /etc/sysconfig/network
	[ ${NETWORKING} = "no" ] && exit 0
fi

[ -x /usr/sbin/lpd ] || exit 0

[ -e /etc/printcap ] || exit 0

RETVAL=0

fixup () {
    # Fixup the printcap file in case it has continuation characters at the
    # end of each entry, like old versions of printtool did.
    if [ -w /etc/printcap ] ; then
    TMP1=`mktemp /etc/printcap.XXXXXX`
    gawk '
        BEGIN { first = 1; cont = 0; last = "" }
        /^[:space:]*#/	{ if(cont) sub("\\\\$", "", last)}
        { if(first == 0) print last }
        { first = 0 }
        { last = $0 }
        { cont = 0 }
        /\\$/ { cont = 1 }
        END {sub("\\\\$", "", last); print last}
    ' /etc/printcap > ${TMP1} && cat ${TMP1} > /etc/printcap && rm -f ${TMP1}
    fi
}

start () {
    echo -n "Starting lpd: "
    # run checkpc to fix whatever lpd would complain about
    /usr/sbin/checkpc -f
    # start daemon
    daemon /usr/sbin/lpd
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch /var/lock/subsys/lpd
    return $RETVAL
}

stop () {
    # stop daemon
    echo -n "Stopping lpd: "
    killproc /usr/sbin/lpd
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f /var/lock/subsys/lpd
    return $RETVAL
}

restart () {
    stop
    start
    RETVAL=$?
    return $RETVAL
}

# See how we were called.
case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    status)
	status /usr/sbin/lpd
	RETVAL=$?
	;;
    restart)
	restart
	;;
    condrestart)
	# only restart if it is already running
	[ -f /var/lock/subsys/lpd ] && restart || :
	;;
    reload)
	echo -n "Reloading lpd: "
	killproc /usr/sbin/lpd -HUP
	RETVAL=$?
	echo
	;;
    fixup)
        fixup
	;;
    *)
        echo "Usage: lpd {start|stop|restart|condrestart|reload|status|fixup}"
        RETVAL=1
esac

exit $RETVAL
