#!/bin/sh

#Variable Initialization
###############################################################################

PHASE2_PPDS=/usr/share/cups/model/Kyocera/
PHASE3_PPDS=/usr/share/ppd/kyocera/
PHASE4_PPDS=/usr/share/kyocera/ppd4/

CUPS_PPDS=/etc/cups/ppds/
KYOCERA_CONFIG=/usr/share/kyocera/

CONFIG_TMP=/tmp/kyocera_config/

#Handle Upgrades
###############################################################################

handle_phase2(){
    if [ -d $PHASE2_PPDS ]; then
        rm -rvf $PHASE2_PPDS
    fi
}

handle_phase3(){
    if [ -d $PHASE3_PPDs ]; then
        rm -rvf $PHASE3_PPDs
    fi
}

handle_phase4(){
    #If Phase 4 is installed we need to handle the upgrade
    #This copies the existing settings config files and 
    #records the installed phase 4 printers
    #The Post-Installer than looks at the list and handles 
    #Reinstalling the printers
    if [ -d $PHASE4_PPDS ]; then
        if [ -d $KYOCERA_CONFIG ]; then
            users=`ls $KYOCERA_CONFIG | grep -v 'ppd4\|ppd5\|appicon\|Python'`
            create_tmp_folders $users
            create_config_copies $user
        fi

        get_installed_ppds
    fi
}

#Phase 4 Handling
###############################################################################

create_tmp_folders(){
    if [ ! -z "$1" ]; then
        for user in ${1}; do
            mkdir -p "$CONFIG_TMP/$user"
        done
    fi
}

create_config_copies(){
    if [ ! -z "$1" ]; then
        for user in ${1}; do
            cp -a $KYOCERA_CONFIG/$user $CONFIG_TMP/
            chown --reference=$KYOCERA_CONFIG/$user $CONFIG_TMP/$user
        done
    fi
}

#Create files in /tmp that describe each phase 4 printer installed
get_installed_ppds(){
    #Search for all installed printers using a kyocera filter
    filters="kyofilter_E\|kyofilter_ras_E\|kyofilter_pdf_E"
    files=`grep -l $filters /etc/cups/ppd/*.ppd 2>/dev/null`
    mkdir /tmp/kyocera_printers 2>/dev/null
    for file in ${files}; do
        #Get the printer name
        ppd=${file#/etc/cups/ppd/}
        printer=${ppd%.ppd}
        #Get the printer address
        stat=`lpstat -v $printer | grep -o ": .*"`
        address=${stat#: }
        #Get the Make and Model
        product=`grep "\*ModelName:" $file | grep -o ": .*"`
        model=${product#: }

        #Output the results into a temporary folder to be read by
        #the postinstall script
        loc=/tmp/kyocera_printers/$printer
        echo $printer > $loc
        echo $address >> $loc
        echo $model >> $loc
        grep "\*DefaultOption" $file | grep -o "Option.*: .*" >> $loc

    done
}

#Execution
###############################################################################

handle_phase2
handle_phase3
handle_phase4
