#!/bin/bash
#
############################################
#
# changeprintername - changes the name of a
#                     printer that was 
#                     created using Ubuntu
#                     Printing GUI
#
# Usage: changeprintername old_name new_name
#
# Written: Naaman Campbell
#          22 November 2005
#
############################################

CUPS_DIR=/etc/cups
CONF=$CUPS_DIR/printers.conf
PPD_DIR=$CUPS_DIR/ppd

# Usage Check
if [ $# -ne 2 ]; then
  echo "Usage: $0 old_name new_name"
  exit
fi

##################################
# DISPLAY CONFIG AND PROMPT USER #
##################################

# find line number of first instance of old printer name
LINE=`grep -m 1 -n $1 $CONF | sed -e 's/^\(.*\)\:.*/\1/'` 

# obtain a magic number for 'tail'
LINECOUNT=`cat $CONF | wc -l`
TAILNUM=`expr $LINECOUNT - $LINE`

# find number of lines between start and end of 
# config section for printer
PATTERN="</Printer>"
NUMOFLINES=`tail -$TAILNUM $CONF | grep -m 1 -n $PATTERN | sed -e 's/^\(.*\)\:.*/\1/'`
ENDLINE=`expr $LINE + $NUMOFLINES`

# display current config to user
echo
echo "Confirm changing the current printer $1 to $2"
echo "with the following configuration.."
echo
sed -n ''$LINE','$ENDLINE' p' $CONF 
echo
echo "Proceed with printer name change? (y or n)"
read answer

case $answer in 
	y)	echo "Changing $1 to $2"
		;;
	n)	echo "Exiting.."
		exit
		;;
	*)	echo "Invalid selection, now exiting.."
		exit
		;;
esac

###################
# PERFORM CHANGES #
###################

# create symlink
echo
echo "Creating symlink.."
ln -s $PPD_DIR/$1.ppd $PPD_DIR/$2.ppd

# update config file
echo "Updating configuration file.."
sed -i -e ''$LINE','$LINE' s/'$1'/'$2'/' $CONF

# restart cups
echo "Restarting CUPS.."
/etc/init.d/cupsys restart

echo "Script completed operations.."
