#! /bin/bash

# Uncomment below line to enable bash script debugging
# set -x

LOG_FILE='/var/log/remotepc/printer.log'
DATA_FILES_PATH='/var/log/remotepc/remotePrinter'

# Output "device discovery" information on stdout
if [ "$#" = "0" ]
then
    echo 'direct remotePrinterBackend:/var/log/remotepc/remotePrinter "RemotePC_Printer" "Remote Printer by RemotePC"'
    exit 0
fi

# -----------------From here normal backend operation starts-----------------

# check and create directory for storing printer files, installer script also creates it, here it is just for safety
if [ ! -d $DATA_FILES_PATH ]
then
    mkdir -p $DATA_FILES_PATH
    chmod 777 $DATA_FILES_PATH
fi

# close stdout and stderr, redirect stdout to log file, and stderr to where stdout is redirected to (i.e. the log file)
exec 1<&-
exec 2<&-
exec 1>>$LOG_FILE
exec 2<&1

# change file permissions to make it readable by all
chmod 644 $LOG_FILE

echo ''
echo ''
echo '=================================================='
echo "Print job received at time: `date`"
# Input can come from a file or stdin, so mark file as stdin in case input comes from file, and then read from stdin (fd0) in any case
if [ -n "$6" ]
then
    exec <"$6"
fi

PDF_FILE="$DATA_FILES_PATH/remotePcPrinterFile-$1.pdf"
echo "INFO: writing data to file $PDF_FILE"

if cat - >$PDF_FILE
then
    echo 'INFO: data write successful'
else
    echo "ERROR: data write failed"
    exit 1
fi

# change mode of file so that host process can access it
chmod 644 $PDF_FILE

# Printer data to be sent to RemotePC daemon, #-delimited string
DATA_TO_BE_SENT="PrinterData#$PDF_FILE"

# if this is new backend, then add viewer machine id and printer name also
if [ ! -z "${VIEWER_MACHINE_ID}" ]
then
    DATA_TO_BE_SENT="${DATA_TO_BE_SENT}#${VIEWER_MACHINE_ID}#${PRINTER_NAME}"
fi

# below are 2 ways to send the output pdf file name to RemotePC daemon
if [ ! -f /opt/remotepc/resources/port.txt ]
then
    echo 'ERROR: The port file for daemon connection is missing.'
    exit 1
fi

PORT=`cat /opt/remotepc/resources/port.txt`

exec {FD}>"/dev/tcp/localhost/$PORT"
echo -ne $DATA_TO_BE_SENT >&$FD
exec {FD}>&-

#echo -n $DATA_TO_BE_SENT | nc localhost $PORT

if [ "$?" != '0' ]
then
    echo "ERROR: Sending filename to daemon failed"
    exit 1
fi

exit 0
