#! /bin/sh
# -*- sh -*-
#
# $ApsCVS: src/apsfilter/bin/aps2file.in,v 1.1.2.7 2002/02/24 20:47:48 andreas Exp $
#
# aps2file, by Michael Loßin
#
# pass input data through apsfilter into a file ("print to file" mode)
#
# doesn't work with fake duplex mode, since two PostScript documents
# (even and odd pages) will end up in one
#

unset Z_OPTS APSFILTER OUTPUT_FILE INPUT_FILE DEBUG
QUEUE=${PRINTER:-lp}


usage()
{
    cat >&2 <<EOF
aps2file: print to file using apsfilter

Usage:
	aps2file [-h] [-D] [-P queue] [-Z options] [-o output] [input]

Options:
	-h		show this help
	-D		run apsfilter in debug mode ('set -x')
	-P queue	name of printer queue to be used for apsfilter
			(default: value of '\$PRINTER'; otherwise 'lp')
	-Z options	comma separated option list
			(default: empty)
	-o output	output file
			(default: stdout)
	input		input file
			(default: stdin)
EOF
    exit 0
}

error()
{
    echo >&2 "aps2file: $@"
    exit 1
}

parse_commandline()
{
    while [ "$1" ]; do
	case "$1" in
	    -P)		shift; QUEUE="$1" ;;
	    -P*)	QUEUE="${1#-P}" ;;

	    -Z)		shift; Z_OPTS="-Z$1" ;;
	    -Z*)	Z_OPTS="$1" ;;

	    -o)		shift; OUTPUT_FILE="$1" ;;
	    -o*)	OUTPUT_FILE="${1#-o}" ;;

	    -h|--help)	usage ;;

	    -D)		DEBUG="-x" ;;

	    -*)		error "unknown option '$1'" ;;

	    *)		if [ "$INPUT_FILE" ]; then
			    error "at most one input file allowed"
			else
			    INPUT_FILE="$1"
			fi ;;
	esac
	shift
    done
}

check_queue_name()
{
    local q

    # apspreview provides a special configuration directory to aps2file
    # (supplied in environment variable APS_CONFDIR) and the proper queue
    # name, so we don't need to re-check it
    if [ -z "$APS_CONFDIR" ]; then
	APS_CONFDIR="/etc/apsfilter"

	# if the queue name is an alias, parse printcap for the original name
	if [ ! -d "$APS_CONFDIR/$QUEUE" ]; then
	    # quote forward slashes
	    q=$(echo "$QUEUE" | sed 's%/%\\/%')
	    q=$("/usr/bin/awk" -F":" "/^${q}[|:]|^[^#].*\|${q}[|:]/,/^#/ \
		{ if (\$0 ~ /:sd=/) print \$2 }" < "/etc/printcap")
	    if [ "$q" ]; then
		QUEUE="${q##*/}"
	    else
		error "couldn't resolve printer name '$QUEUE' in /etc/printcap"
	    fi
	fi
    fi
}

print2file()
{
    APSFILTER="$APS_CONFDIR/basedir/bin/apsfilter"
    if [ ! -x "$APSFILTER" ]; then
	error "apsfilter not found at '$APSFILTER'"
    elif [ ! -f "$APS_CONFDIR/$QUEUE/apsfilterrc" ]; then
	error "no configuration file found for queue '$QUEUE'"
    fi

    : ${INPUT_FILE:=/dev/stdin} ${OUTPUT_FILE:=/dev/stdout}

    # start with an almost empty environment to emulate running under LPRng;
    # input must not come from a file connected to a terminal
    cat "$INPUT_FILE" | env -i CONTROL=dummy APS2FILE_CONTEXT=dummy \
	SPOOL_DIR="$QUEUE" "/bin/sh" $DEBUG "$APSFILTER" -h"$HOSTNAME" \
	-n"$USER" -f$(basename "$INPUT_FILE") $Z_OPTS > "$OUTPUT_FILE"
}

#
# main controls
#

parse_commandline "$@"
check_queue_name
print2file
