#!/bin/sh
#
# Copyright (c) 1994, 1995, 1996 by Sun Microsystems, Inc.
# All  Rights Reserved
#
#	@(#)conv_lp	1.10	96/04/22 SMI
#
#	This script will automatically generate a "printcap" file
#	from the currently configured LP printer configuration.
#
PATH=/bin:/usr/bin:/usr/sbin

export PATH
umask 022

set -- `getopt d:f: $*`
if [ $? != 0 ] ; then
	echo "Usage: $0 [-d dir] [-f file]"
	exit 1
fi

for OPTION in $*
do
	case $OPTION in
	-f) SYSTEM_FILE=$2; shift 2;;
	-d) BASE_DIR=$2; shift 2;;
	--) shift; break;;
	esac
done

SYSTEM_FILE=${SYSTEM_FILE:-"${BASE_DIR}/etc/printers.conf"}

if [ ! -d ${BASE_DIR}/etc/lp/printers ] ; then
	echo "Exit $0: There is no directory ${BASE_DIR}/etc/lp/printers"
	echo "\tfrom which to create /etc/printers.conf."
	exit 0
fi

if [ -f ${BASE_DIR}/etc/lp/default ] ; then
	DEFAULT_PRINTER=`cat ${BASE_DIR}/etc/lp/default`
	lpset -n system -a "use=${DEFAULT_PRINTER}" _default
	mv ${BASE_DIR}/etc/lp/default ${BASE_DIR}/etc/default.orig
fi

cd ${BASE_DIR}/etc/lp/printers	# get the list of locally configured printers
PRINTERS=`echo *`

for PRINTER in ${PRINTERS}	# for each printer get config info
do
    if [ "${PRINTER}" = "*" ] ; then
	continue
    fi

    RNAME=${PRINTER}
    DESC=""
    RHOST=""

    if [ -f ${PRINTER}/comment ] ; then
	    DESC=`cat ${PRINTER}/comment`
    fi

    REMOTE=`grep Remote: ${PRINTER}/configuration 2>/dev/null | sed -e "s/^Remote: //"`
    DEVICE=`grep Device: ${PRINTER}/configuration 2>/dev/null | sed -e "s/^Device: //"`

    if [ -n "${DEVICE}" ] ; then
	RHOST=`uname -n`
    elif [ `echo ${REMOTE} | grep -c \!` -ne 0 ] ; then
	RHOST=`echo $REMOTE | cut -d \! -f 1`
	RNAME=`echo $REMOTE | cut -d \! -f 2`
    else
	RHOST=${REMOTE}
    fi

    lpset -n system -a "bsdaddr=${RHOST},${RNAME}" -a "description=${DESC}" \
	${PRINTER}

done

exit 0
