#!/bin/bash

#inspiré par /var/lib/dpkg/info/cups-pdf.postinst et /var/lib/dpkg/info/cups-pdf.postrm

[ "$(CreoleGet activer_cups)" = "non" ] && exit 0

LPSTAT=$(CreoleRun "LC_ALL=C lpstat -h localhost -v 2> /dev/null| grep 'cups-pdf:/'" "fichier")
SIZE="A4"

activated=$(CreoleGet cups_pdf)

function add_printer() {
    aqueue=$1
    shared=$2
    # Create the queue.
    CreoleRun "lpadmin -h localhost -p $aqueue -v cups-pdf:/ -m lsb/usr/cups-pdf/CUPS-PDF_opt.ppd -o printer-is-shared=$shared -o PageSize=$SIZE" "fichier"
    # Enable the queue.
    CreoleRun "cupsenable -h localhost $aqueue" "fichier"
    CreoleRun "cupsaccept -h localhost $aqueue" "fichier"
    #reload
    CreoleRun "LC_ALL=C lpoptions -h localhost -d $aqueue &>/dev/null" "fichier"
}

function del_printer() {
    dqueue=$1
    moveto=$2
    CreoleRun "cupsreject -h localhost $dqueue" "fichier"
    CreoleRun "cupsdisable -h localhost $dqueue" "fichier"
    [ -n "$moveto" ] && CreoleRun "lpmove -h localhost $dqueue $moveto" "fichier"
    CreoleRun "lpadmin -h localhost -x $dqueue" "fichier"
}

if [ "$(CreoleGet cups_pdf)" = "oui" ]; then
    queue=$(CreoleGet cups_pdf_name)
    shared=$(CreoleGet cups_pdf_shared)
    if [ -z "$LPSTAT" ]
    then
        add_printer $queue "$shared"
    elif [ "${LPSTAT:0:11}" = "device for " ]; then
        #rename printer
        old_queue=$(echo ${LPSTAT:11}|cut -d':' -f1)
        if [ "$queue" = "$old_queue" ]; then
            #do nothing
            echo -n ''
        elif [ "$(echo $queue | tr a-z A-Z)" = "$(echo $old_queue | tr a-z A-Z)" ]; then
            #change case (cups is case insensitive)
            del_printer $old_queue
            add_printer $queue "$shared"
        else
            #rename
            add_printer $queue "$shared"
            del_printer $old_queue $queue
        fi
    fi
    #if shared option is different
    old_shared=$(CreoleRun "lpoptions -h localhost -p $queue|sed 's/ /\n/g'|grep printer-is-shared|cut -d'=' -f2" "fichier")
    if [ ! "$shared" = "$old_shared" ]; then
        CreoleRun "lpoptions -h localhost -p $queue -o printer-is-shared=$shared" "fichier"
    fi
    # Set the PDF queue as default if there is no default printer yet.
    LPSTATD=$(CreoleRun "LC_ALL=C lpstat -h localhost -d 2>/dev/null | grep 'system default destination:'" "fichier")
    if [ -z "$LPSTATD" ]
    then
        CreoleRun "lpadmin -h localhost -d $queue" "fichier"
    fi
else
    if [ "${LPSTAT:0:11}" = "device for " ]; then
        del_printer "$(echo ${LPSTAT:11}|cut -d':' -f1)"
    fi
fi

exit 0
