#! /bin/sh

set -e

# Debconf
. /usr/share/debconf/confmodule

if [ "$1" = configure ]; then
    # set up custom PPD directory
    if ! dpkg-statoverride --list /usr/share/ppd/custom > /dev/null
    then
        chown root:lpadmin /usr/share/ppd/custom 2>/dev/null || true
        chmod 3775 /usr/share/ppd/custom 2>/dev/null || true
    fi

    # Generate raw MIME handling files if they don't already exist.
    if [ ! -e /etc/cups/raw.types ]; then
	cat >/etc/cups/raw.types <<EOF
# This file was generated by the cups package.  You may change it, or
# reconfigure this file with dpkg-reconfigure.  If it is removed, it
# will be regenerated by the package scripts.

application/octet-stream
EOF
    fi
    if [ ! -e /etc/cups/raw.convs ]; then
	cat >/etc/cups/raw.convs <<EOF
# This file was generated by the cups package.  You may change it, or
# reconfigure this file with dpkg-reconfigure.  If it is removed, it
# will be regenerated by the package scripts.

application/octet-stream	application/vnd.cups-raw	0	-
EOF
    fi

    # Set up raw printing of application/octet-stream if desired.
    db_fget cupsys/raw-print changed
    if [ "$RET" = "true" ]; then
	mv /etc/cups/raw.convs /etc/cups/raw.convs-convert
	db_get cupsys/raw-print
	if [ "$RET" = "true" ]; then
	    sed 's/^\s*#\s*application/application/' \
		< /etc/cups/raw.convs-convert > /etc/cups/raw.convs
	else
	    sed 's/^application/#application/' \
		< /etc/cups/raw.convs-convert > /etc/cups/raw.convs
	fi
	rm -f /etc/cups/raw.convs-convert
	db_fset cupsys/raw-print changed false
    fi
    # Set up backends
    db_get cupsys/backend && SELECTED=$RET
    # We remove the scsi backend from the output as it got removed in CUPS 1.5.0
    # We also remove the IPP backends as they are statically in cups-daemon now
    list=`echo $SELECTED | sed -e 's/, /,/g' | sed -e 's/scsi,*\b//g' | sed -e 's/ipp,*\b//g' | sed -e 's/ipps,*\b//g' | sed -e 's/ipp14,*\b//g' | sed -e 's/parallel,*\b//g' | sed -e 's/serial,*\b//g'`
    save_IFS=$IFS
    IFS=,
    (cd /usr/lib/cups/backend && rm -f lpd socket usb snmp dnssd mdns)
    for module in $list; do
      ln /usr/lib/cups/backend-available/$module /usr/lib/cups/backend/$module
      if [ "$module" = "dnssd" ]; then
	ln /usr/lib/cups/backend/dnssd /usr/lib/cups/backend/mdns
      fi
    done
    IFS=$save_IFS

    # activate new backends on upgrades
    db_fset cupsys/backend changed false

    # Resync Debconf database with real state
    list=`( cd /usr/lib/cups/backend && for f in lpd socket usb snmp dnssd; do [ -e $f ] && echo -n "$f, "; done ) | sed -e 's/, $//'`
    db_set cupsys/backend $list;
fi

#DEBHELPER#

# ppd_updater is supposed to be launched only with a running CUPS.
ppd_updater () {
	driverregexp="$1"
	gennicknameregexp="$2"

	[ ! -z "$gennicknameregexp" ] && \
	    gennicknameregexp="; $gennicknameregexp"
	gennicknameregexp='s/\s*\(recommended\)//'"$gennicknameregexp"
	tmpfile1=`mktemp -t updateppds.XXXXXX`
	tempfiles="$tempfiles $tmpfile1"
	grep -E $driverregexp $tmpfile0 > $tmpfile1 || :
	cd /etc/cups/ppd
	for ppd in *.ppd; do
	    [ -r "$ppd" ] || continue
	    queue=${ppd%.ppd}
	    lpstat -h /run/cups/cups.sock -p "$queue" >/dev/null 2>&1 || continue
	    nickname=`grep '\*NickName:' "$ppd" | cut -d '"' -f 2 | perl -p -e 's/\n$//' | perl -p -e "$gennicknameregexp" | perl -p -e 's/(\W)/\\\\$1/g'`
	    lang=`grep '\*LanguageVersion:' "$ppd" | cut -d ' ' -f 2 | perl -e 'print lc(<>)' | perl -p -e 's/[\r\n]//gs'`
	    ppdfound="0"
	    englishppduri=""
	    tmpfile2=`mktemp -t updateppds.XXXXXX`
	    tempfiles="$tempfiles $tmpfile2"
	    cat $tmpfile1 | perl -p -e "$gennicknameregexp; s/\n*$/\n/s" | grep -E '^\S+\s+.*'"$nickname"'$' | cut -d ' ' -f 1 > $tmpfile2
	    while read newppduri; do
		[ "$ppdfound" = "0" ] && lpadmin -h /run/cups/cups.sock -p "$queue" -m $newppduri 2>/dev/null || continue
		newlang=`grep '\*LanguageVersion:' "$ppd" | cut -d ' ' -f 2 | perl -e 'print lc(<>)' | perl -p -e 's/[\r\n]//gs'`
		[ "$newlang" = "$lang" ] && ppdfound="1"
		[ "$newlang" = "english" ] && englishppduri="$newppduri"
	    done < $tmpfile2
	    [ "$ppdfound" = "0" ] && [ ! -z "$englishppduri" ] && lpadmin -h /run/cups/cups.sock -p "$queue" -m $englishppduri 2>/dev/null && ppdfound="1"
	    [ "$ppdfound" = "1" ] && echo PPD for printer $queue updated >&2
	done
	return 0
}

# Do the following only if CUPS is running and the needed CUPS tools
# are available
if which lpstat > /dev/null 2>&1 && \
	which lpinfo > /dev/null 2>&1 && \
	which lpadmin > /dev/null 2>&1 && \
	LC_ALL=C lpstat -h /run/cups/cups.sock -r | grep -v not > /dev/null 2>&1; then

	tempfiles=
	trap 'rm -f $tempfiles; exit 0' 0 HUP INT QUIT ILL ABRT PIPE TERM
	tmpfile0=`mktemp -t updateppds.XXXXXX`
	tempfiles="$tempfiles $tmpfile0"

	lpinfo -h /run/cups/cups.sock -m > $tmpfile0

	if [ "$1" = configure ] ; then
		# Update CUPS included drivers' queues
		echo "Updating PPD files for cups ..."
		ppd_updater 'lsb/usr/cups-included/|drv:///sample.drv/' 's/,\s*\d+\.\d+[\d\.]*$//i'
	fi
	if [ "$1" = triggered ] || [ "$1" = configure ] ; then
		# Update external drivers' queues.
		# 
		# We log the modification dates of the file in 
		# /usr/share/cups/ppd-updaters/* after updating the PPDs 
		# according to them. These dates are more or less the creation
		# dates of the driver packages. Then we only update the PPDs of
		# packages, where the /usr/share/cups/ppd-updaters/* file has a
		# modification date different to the logged date as this means
		# that a fresh /usr/share/cups/ppd-updaters/* file and
		# therefore a fresh package got installed. This avoids updating
		# of PPDs when the corresponding package was not changed.
	        logfile=/var/cache/cups/ppd-updates
		touch $logfile
		for driverfile in `ls /usr/share/cups/ppd-updaters`; do
		        driver=`echo $driverfile | perl -p -e 's/\.ppd-updater$//' | perl -p -e 's/^printer-driver-//'`
			modtime=`ls -l --time-style=+%s /usr/share/cups/ppd-updaters/$driverfile | perl -p -e 's/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(\S+)\s+(\S+)\s*$/$1\n/'`
			oldmodtime=`cat $logfile | grep " $driver$" | cut -d ' ' -f 1`
			if [ "$modtime" != "$oldmodtime" ]; then
				echo "Updating PPD files for $driver ..."
				. /usr/share/cups/ppd-updaters/${driverfile}
				ppd_updater "${DRIVER_REGEXP}" "${GENNICKNAME_REGEXP}"
				cat $logfile | grep -v " $driver$" > $logfile.new || touch $logfile.new
				echo "$modtime $driver" >> $logfile.new
				mv $logfile.new $logfile
			fi
		done
	fi
fi

db_stop
exit 0
