#! /bin/sh
#
# Brother Print filter
# Copyright (C) 2005 Brother. Industries, Ltd.

# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA  02111-1307  USA
#############################

PRINTER="HL4040CN"
PRINTER_LOW=`echo $PRINTER | tr [:upper:] [:lower:]`

#####################################

if [ "$1" = '-e' ]; then
  	lpadmin -x $PRINTER
	if [  -e /etc/init.d/cups ]; then
		/etc/init.d/cups restart
	elif [  -e /etc/init.d/cupsys ]; then
		/etc/init.d/cupsys restart
	fi
#  	/etc/init.d/cups restart
  	exit 0
fi
if [ "$1" = "help" ] || [ "$1" = "-h" ]; then
  echo   'option -h : help'
  echo   '       -i : install printer'
  echo   '       -e : remove printer'
  exit 0
fi

if [ -e "/usr/local/Brother/Printer/${PRINTER_LOW}/lpd/filter${PRINTER_LOW}" ]; then
  :
else
  echo "ERROR : Brother ${PRINTER} LPD filter is not installed."
fi

chmod a+w /usr/local/Brother/Printer/${PRINTER_LOW}/inf/br${PRINTER_LOW}rc
chmod a+w /usr/local/Brother/Printer/${PRINTER_LOW}/inf
if [ -e /etc/init.d/lpd ]; then
   /etc/init.d/lpd stop
fi
if [  -e /etc/init.d/lprng ]; then
   /etc/init.d/lprng stop
fi
if [  -e /etc/init.d/cups ]; then
   /etc/init.d/cups restart
elif [  -e /etc/init.d/cupsys ]; then
   /etc/init.d/cupsys restart
fi

sleep 2s

port2=`lpinfo -v | grep -i "usb://Brother/${PRINTER_LOW}" | head -1`
if [ "$port2" = '' ];then
    port2=`lpinfo -v | grep 'usb://Brother' | head -1`
fi

if [ "$port2" = '' ];then
    port2=`lpinfo -v | grep 'usb://' | head -1`
fi
port=`echo $port2| sed s/direct//g`

if [ "$port" = '' ];then
    port=usb:/dev/usb/lp0
fi

lpadmin -p ${PRINTER} -E -v $port -m br${PRINTER_LOW}.ppd
exit 0

