#!/bin/bash

set -e -u

LOG=log.txt
QUEUE=Save_As_PDF
CPDBDEMO=/usr/bin/print_frontend
FILE_TO_PRINT=/usr/share/cups/data/default-testpage.pdf
OUTPUT_FILE=test.pdf
#CUPS_SPOOL_DIR=/var/spool/cups

# Create temporary work directory
WORKDIR=$(mktemp -d)
cd $WORKDIR

cleanup() {
    # Remove the log file
    rm -f $LOG
    # Remove the temporary directory
    rm -rf $WORKDIR
    # Delete the printer
    #lpadmin -x $QUEUE 2>/dev/null || :
}

trap cleanup 0 EXIT INT QUIT ABRT PIPE TERM

# Create the log file
rm -f $LOG
touch $LOG

# Configure the running CUPS server to do debug2 logging
#sed -e 's/^.*LogLevel.*$/LogLevel debug2/g' -i /etc/cups/cupsd.conf
# Configure the running CUPS server to set FileDevice to Yes
#sed -e 's/^.*FileDevice.*$/FileDevice Yes/g' -i /etc/cups/cups-files.conf
# Configure the running CUPS server to allow root to do administrative tasks
#sed -e 's/^.*SystemGroup.*$/SystemGroup lpadmin root/g' -i /etc/cups/cups-files.conf
#service cups restart

# Create a test print queue (disabled, but accepting jobs)
#cupsctl --debug-logging
#lpadmin -p $QUEUE -v file:/dev/null -m drv:///sample.drv/laserjet.ppd -o PageSize=Env10 2>/dev/null
#cupsaccept $QUEUE


# Wait for CUPS to DNS-SD-broadcast the queue
#sleep 5

# Run the demo with a session D-Bus and feed in commands, in parallel
# do a kill on the demo process after a timeout, for the case that the
# commands take too long or stopping the demo does not work. Ignore the
# error of the kill command if the demo gets stopped correctly.
( \
  sleep 1; \
  echo get-all-options $QUEUE FILE; \
  echo print-file $FILE_TO_PRINT $QUEUE FILE; \
  echo $OUTPUT_FILE; \
  sleep 1; \
  echo stop \
) | dbus-run-session -- $CPDBDEMO >> $LOG 2>&1

cat $LOG

echo

# Does the printer appear in the initial list of available printers?
echo "Initial listing of the printer:"
( grep '\*\* Message:.*: *Printer '$QUEUE'$' $LOG ) || \
    ( echo "CUPS queue $QUEUE not listed!"; \
      exit 1 )

echo

# Is the list of options empty?
echo "Option list empty:"
( grep 'Retrieved 0 options' $LOG ) || \
    ( echo "Backend has options!"; \
      exit 1 )

echo

# Did the successful submission of a print job get confirmed?
echo "Confirmation message for job submission:"
( grep -i 'File printed successfully' $LOG ) || \
    ( echo "No confirmation of job submission!"; \
      exit 1 )

echo

exit 0
