#!/bin/bash

FROM=""
NAME=""
PAGE=a4
FAXPRG=/usr/sbin/sendfax
LOGDIR=/var/log/hylafax
FAXSTAT=/usr/bin/faxstat

#
# This is fax4CUPS 1.29, a fax back end for CUPS
#
# Copyright (C) 2001-2010 Sebastiano Vigna <vigna@acm.org>
#
#   This program is free software; you can redistribute it and/or modify it
#   under the terms of the GNU General Public License as published by the Free
#   Software Foundation; either version 2 of the License, or (at your option)
#   any later version.
#
#   This program is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
#   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
#   for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Modified by Michael Goffioul <goffioul at imec dot be>
#
#   - phone number as option instead of job name: "-o phone=<number>"
#
# Modified by Arnold Moene <a.f.moene at eduphys dot xs4all dot nl>
#
# - This is a hacked version of the fax back end, to make it work for 
#   a local HylaFAX server 
#
# Additional fixes by Kevin Ivory <Ivory at SerNet dot de>
#
# Fixes and better cleanup by Diab Jerius <jerius at comcast dot net>
#

# Called with no arguments, we list the provided HylaFAX back end
# (serial devices are irrelevant here).
if [ $# -eq 0 ]; then
	if [ ! -x "$FAXPRG" ]; then 
		echo "ERROR: Can't find HylaFAX program $FAXPRG" 1>&2
		exit 0
	fi
	echo "direct hylafax:/local \"Unknown\" \"Local HylaFAX server\""
	exit 0
fi

# Get the user that owns the job
USER=$2
FROM=$USER

# Apparently the first character emitted is somehow "eaten" by the reader
echo 1>&2

# If we find six arguments, the last one is the fax name;
# otherwise, it is empty and sendfax will read standard input.
FAXNAME=$6

# If we are using an actual file, we copy it elsewhere.
if [ $# -eq 6 ]; then
	TMPNAME=$(mktemp </dev/null /tmp/fax.XXXXXX) || ( echo "ERROR: Failed to create temporary file" 1>&2; exit 2 )
	cp -f $FAXNAME $TMPNAME </dev/null >>$LOGDIR/$FAXNAME.log 2>&1 || ( echo "ERROR: Failed to copy temporary file" 1>&2; exit 2 )
	chown $USER $TMPNAME </dev/null >>$LOGDIR/$FAXNAME.log 2>&1 || ( echo "ERROR: Failed to chown temporary file" 1>&2; exit 2 )
	FAXNAME=$TMPNAME
fi

# Set some defaults
RES="-m"	# Default resolution is high; set this to -l for low resolution
NUMBER=""	# Use option "phone" as number by default

# Parse user-specified options from the PostScript file and set -l/-m
function getSelectedOption() {
	for i in $@; do
		case $i in
			\**) SELOPT=${i#[*]}; return ;;
		esac
	done
}

function parseOptions() {
	while read LINE; do 
		MAIN=${LINE%%:*}
		OPTIONS=${LINE##*:}
		getSelectedOption $OPTIONS
		case $MAIN in
			PageSize/*) echo "PAGE=$(echo -n "$SELOPT" | tr '[:upper:]' '[:lower:]')" ;;
			Resolution/*) if [ "$SELOPT" == "204x98dpi" ]; then echo "RES=-l"; fi ;;
			Dial/*) if [ "$SELOPT" == "Manually" ]; then echo "NUMBER=-m"; elif [ "$SELOPT" == "JobName" ]; then echo "NUMBER=-j"; fi ;;
		esac
	done
}

eval $(lpoptions -p $PRINTER -l | parseOptions)
if [ "$NUMBER" == "-j" ]; then 
	NUMBER="$3" 
fi

# Scan user options and set -l/-m (override previous choices if necessary)
for opt in $5; do
	case "$opt" in
		lowres*)  RES="-l" ;;
		hires*)   RES="" ;;
		manual*)  NUMBER="-m" ;;
		jobname*) NUMBER="$3" ;;
		phone=*)  NUMBER="${opt#phone=}" ;;
		media=*)  PAGE=$(echo ${opt#media=}|tr '[:upper:]' '[:lower:]') ;;
	esac
done

# do some checking before continuing
RUNNING=$($FAXSTAT -s|grep HylaFAX|grep Running)
if [ -z "$NUMBER" ]; then
	echo "ERROR: Empty phone number"  1>&2
	exit 2
elif [ ! -x "$FAXPRG" ]; then
	echo "ERROR: $FAXPRG: executable not found"  1>&2
	exit 2
elif [ "$NUMBER" == "(stdin)" ]; then
	echo "ERROR: (stdin) is not a valid phone number" 1>&2
	exit 2
elif [ "$NUMBER" == "stdin" ]; then
	echo "ERROR: stdin is not a valid phone number" 1>&2
	exit 2
elif [ -z "$RUNNING" ]; then
	echo "ERROR: HylaFAX not running"  1>&2
	exit 2
fi

# Remove possible whitespace in number: replace by period
NUMBER=${NUMBER// /.}

# Use sudo to make sure that job is owned by the user that wants to "print",
# not root. This is needed so that the owner of the job can remove it if needed.
sudo -u $USER $FAXPRG -s $PAGE $RES -n -f $FROM -d $NUMBER $FAXNAME >>$LOGDIR/$FAXNAME.log 2>&1

RC=$?
case $RC in
	0) echo "INFO: Fax sent" 1>&2 ;;
	# I do not know the return values of sendfax
	*) echo "ERROR: Unknown error (return code $RC)" 1>&2 ;;
esac

exit $RC
