#!/bin/sh
# This script installs the SafeCom pullprint print queue
# for Høgskolen i Gjøvik on Linux and Mac systems.
# Written by einarh@hig.no
# I consider this script public domain

# Test for system variant
OS=$(uname)
if [ "${OS}" != "Darwin" ] && [ "${OS}" != "Linux" ]; then
	echo "I don't think I can run on "${OS}", but if you insist, please edit me and remove the test." 1>&2
	exit 1
fi

# Test for root
if [ $(id -u) -ne 0 ]; then
	echo "This script must be run as root. Please use sudo or log in as root" 1>&2
	exit 1
fi

# Test for CUPS
command -v lpadmin >/dev/null 2>&1 
if [ $? -ne 0 ]; then 
	echo "You must have CUPS installed to add printers. Please install CUPS." 1>&2
	exit 1
fi

# Test for smbclient if on Linux
if [ "${OS}" = "Linux" ]; then
	command -v smbclient >/dev/null 2>&1 
	if [ $? -ne 0 ]; then
		echo "You must have smbclient installed to add printers. Please install smbclient." 1>&2
		exit 1   
	fi
fi

echo "This script will add a new printer called Pullprint, connecting to 
the print server safecom2.hig.no using your normal user name and 
password from HiG. Do not use on multi user systems!"

printf "User name: "
read USERNAME
printf "Password: "
SETTINGS=$(stty -g)
stty -echo
read PASSWORD
stty "${SETTINGS}"

echo ""

# Test for valid username and password if on Linux
if [ "${OS}" = "Linux" ]; then
	smbclient -U HIG/${USERNAME}%${PASSWORD} -L //hig.no > /dev/null 2>&1
	if [ $? -ne 0 ]; then
		echo "User name or password incorrect, or no contact with HiG servers." 1>&2
		exit 1
	fi
fi

# Add the printer

# The Linux way
if [ "${OS}" = "Linux" ]; then
	lpadmin	-p Pullprint \
        	-D "SafeCom Pullprint ved HiG" \
	        -v "smb://hig%5C${USERNAME}:${PASSWORD}@safecom2.hig.no/PullPrint" \
        	-m "drv:///sample.drv/generic.ppd" \
	        -u allow:all -E
fi

# The OSX way
if [ "${OS}" = "Darwin" ]; then
	lpadmin -p Pullprint \
		-D "SafeCom Pullprint ved HiG" \
		-v "smb://HIG;${USERNAME}:${PASSWORD}@safecom2.hig.no/PullPrint" \
		-m "drv:///sample.drv/generic.ppd" \
		-u allow:all -E
fi

if [ $? -ne 0 ]; then
	echo "Could not connect to printer share. See above error for details." 1>&2
	exit 1
fi
                
# Set correct paper size and enable the duplexer option
lpadmin -p Pullprint -o PageSize=A4 -o Option1=True

if [ $? -ne 0 ]; then
	echo "Could not set default options. See above error for details." 1>&2
	exit 1
fi

# Set as default
lpadmin -d Pullprint

if [ $? -ne 0 ]; then
	echo "Could not set Pullprint as default printer. See above error for details." 1>&2
	exit 1
fi

echo "Printer successfully installed."
