#!/bin/bash

set -e -u

LOG=log.txt
QUEUE=Save_As_PDF
FRONTEND=/usr/bin/cpdb-text-frontend
FILE_TO_PRINT=/usr/share/cups/data/default-testpage.pdf
OUTPUT_FILE=test.pdf

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

cleanup() {
    # Remove the log file
    rm -f $LOG
    # Remove the temporary directory
    rm -rf $WORKDIR
}

trap cleanup 0 EXIT INT QUIT ABRT PIPE TERM

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

# 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 -- $FRONTEND >> $LOG 2>&1

cat $LOG

echo

# Does the printer appear in the initial list of available printers?
echo "Initial listing of the printer:"
( grep '^Printer '$QUEUE'$' $LOG ) || \
    ( echo "Printer $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 "Print file actually written and identical with input file:"
if [ ! -r $OUTPUT_FILE ]; then
    echo "Print file not written!"
    exit 1
else
    ls -l $OUTPUT_FILE
fi
if ! diff -q "$FILE_TO_PRINT" "$OUTPUT_FILE"; then
    echo "Print file and input file differ!"
    exit 1
else
    echo "File correctly printed!"
fi

echo

exit 0
