#!/bin/sh -e

# Author: Martin Pitt <martin.pitt@ubuntu.com>
# (C) 2005  Canonical Ltd.
#
# Configure CUPS IPP LAN printer sharing; this is only possible if
# cups.d/ports.conf is included by cupsd.conf and "Listen" is present in
# ports.conf (i. e. sharing_status returns 0 or 1). If the setting
# changed, CUPS will be restarted.
#
# Argument:
# 0: disable sharing 
# 1: enabled sharing
# Return 0 on success, or 1 on failure (prints error to stderr)

STATUS_SCRIPT=/usr/share/cups/sharing_status
PORTSCONF=/etc/cups/cups.d/ports.conf

[ -x $STATUS_SCRIPT ] || {
    echo "Error: cannot execute $STATUS_SCRIPT" >&2
    exit 1
}

set +e
$STATUS_SCRIPT
STATUS=$?
set -e

case "$1" in
    0)
	NEWVAL=Off
	;;
    1)
	NEWVAL=On
	;;
    *)
	echo "Invalid argument (must be 0 or 1)" >&2
	exit 1
	;;
esac

[ $STATUS = 0 -o $STATUS = 1 ] || {
    echo "Error: cannot modify custom configuration" >&2
    exit 1
}

# nothing to do?
[ $1 != $STATUS ] || exit 0


if [ $1 = 0 ]; then
	sed -ri "s/^[[:space:]]*(Port|Listen)[[:space:]]+631\\>/Listen localhost:631/i" $PORTSCONF
else
	sed -ri "s/^[[:space:]]*Listen[[:space:]]+localhost:631\\>/Listen 631/i" $PORTSCONF
fi
	

# restart CUPS
# Automatically added by dh_installinit
if [ -x "/etc/init.d/cupsys" ]; then
    if [ -x /usr/sbin/invoke-rc.d ]; then
	invoke-rc.d cupsys restart || exit 0
    else
	/etc/init.d/cupsys restart || exit 0
    fi
fi
