#!/bin/sh

# Set the CUPS permissions such that anyone can add/remove jobs
# from the queue for gutenbach.

if [ -e /usr/lib/gutenbach/config/printername ]; then
    printername="$(cat /usr/lib/gutenbach/config/printername)"

    conffile="/etc/cups/cupsd.conf"
    mv "$conffile" "$conffile.bak"
    touch "$conffile"

    while read line; do
	listen_localhost=$(echo "$line" | grep '^Listen localhost' || true)
	if [ -n "$listen_localhost" ]; then
	    echo "#GUTENBACH$line" >> "$conffile"
       	else
	    root_location=$(echo "$line" | grep '^<Location />$' || true)
	    if [ -n "$root_location" ]; then
		echo "<Location />" >> "$conffile"
		echo "Allow from All # added by Gutenbach" >> "$conffile"
	    else
		echo "$line" >> "$conffile"
	    fi
	fi

    done < "$conffile.bak"
    rm "$conffile.bak"

    cat >> "$conffile" <<EOF
# Begin configurations for gutenbach

Group audio
Listen *
ServerAlias *

<Location /printers/$printername>
    <Limit Cancel-Job Purge-Jobs CUPS-Authenticate-Job>
        Order deny,allow
        Allow from All
    </Limit>

    Order Deny, Allow
    Allow from All
</Location>

# End configurations for gutenbach
EOF

    /etc/init.d/cups reload

else
    echo "Error: /usr/lib/gutenbach/config/printername does not exist"
    exit 1
fi
