#!/bin/bash
# Ver 1.6
# Wrote by Samson Mok.
# History:
#   2012-01-05
#   2015-02-16  change to template, add net port
#   2016-01-06  add 64-bit filter
#   2016-04-29  change filter name

if [ `id -u` -ne 0 ];then
	sudo $0 $*
	exit
fi
FILTER_PATH=/usr/lib/cups/filter
PPD_NAME=mp220d.ppd
MFG=`grep Manufacturer $PPD_NAME 2>/dev/null|sed 's/.\+\"\(.*\)\".*/\1/'`
MDL=`grep Product $PPD_NAME 2>/dev/null|sed 's/.\+\"(\(.\+\))\".*/\1/'`
if [ -z "$MFG" ];then
	if [ -z "$MDL" ];then
		echo "$PPD_NAME is invalid!"
		exit
	else
		NAME="$MDL"
	fi
else
	NAME="$MFG-$MDL"
fi
NAME=`echo $NAME|sed 's/ /-/'` #convert blanks
MFG2=`echo $MFG|sed 's/ /%20/'`
MDL2=`echo $MDL|sed 's/ /%20/'`
[ $# -ge 1 ] && NAME=$1
[ $# -ge 2 ] && PORT=$2
if [ -z $PORT ];then
	lpstat -v 2>/dev/null|grep -q "$NAME" && EXIST=true
	clear
	echo "Prepare to install '$NAME', and select a port:"
	echo "  1. Serial Port (ttyS0)"
	echo "  2. Parallel Port (lp0)"
	echo "  3. USB Port"
	echo "  4. Ethernet Port"
	echo "  ============================"
	test $EXIST && echo "  d. Delete Exists"
	echo "  q. Exit without installation"
	echo
	while true;do
		read -p "Select: " IN
		case $IN in 1)
			PORT=serial:/dev/ttyS0?baud=9600+bits=8+parity=none+flow=hard
			break
			;;
		2)
			PORT=parallel:/dev/lp0
			break
			;;
		3)
			echo "checking USB connection ..."
			USB_STR=`lpinfo --timeout 3 -v|grep usb|cut -d' ' -f2`
			[ $USB_STR ] && PORT=$USB_STR || PORT="usb://$MFG2/$MDL2"
			break
			;;
		4)
			read -p "Enter IP address and port in the form x.x.x.x:x " ADDR
			PORT=socket://$ADDR
			break
			;;
		d|D)
			if [ $EXIST ];then
				lpadmin -x $NAME
				exit
			fi
			;;
		q|Q)
			echo
			exit
			;;
		esac
	done
fi
DST_FILTER_NAME=rastertojmdot
case $(uname -m) in
	x86_64)
		SRC_FILTER_NAME=rastertojmdot.64
		;;
	*)
		SRC_FILTER_NAME=rastertojmdot
		;;
esac
echo "installing $NAME ..."
if [ -f $FILTER_PATH/$DST_FILTER_NAME ];then
	echo The filter exists.
fi
echo copying filter ...
cp -f $SRC_FILTER_NAME $FILTER_PATH/$DST_FILTER_NAME
[ $? ] && chmod 755 $FILTER_PATH/$DST_FILTER_NAME
WANT_INST=yes
lpstat -p "$NAME" &>/dev/null && WANT_INST=no
if [ $WANT_INST == yes ];then
	echo installing PPD ...
	lpadmin -p "$NAME" -P $PPD_NAME -v $PORT -E
	[ $? ] && lpadmin -d "$NAME"
	[ $? ] && echo "$NAME is connected to $PORT"
else
	echo The printer driver exists.
fi
echo Finished!
echo You can browse 'http://localhost:631' and manage it!
