#!/bin/bash
#
# /usr/lib/lpdfilter/filter/pdf2ps
#
# filter used by /usr/lib/lpdfilter/bin/if
#
# Copyright 2000 SuSE GmbH, Nuernberg Germany
#
# Author: Werner Fink <feedback@suse.de>
#

#
# Activate debugging if requested.
#
if test "$DEBUG" = "medium" -o "$DEBUG" = "high" ; then
    # bash should be verbose
    set -x
    # Redirect stderr to a file
    exec 2> $(mktemp /tmp/lpdfilter.${0##*/}-$$.XXXXXX) || exit 2
fi

#
# Get our environment
#
. /usr/lib/lpdfilter/global/signals
. /usr/lib/lpdfilter/global/functions
type -p readpc   &> /dev/null || export PATH=/usr/lib/lpdfilter/bin:${PATH}
type -p xpmtoppm &> /dev/null || export PATH=${PATH}:/usr/X11R6/bin

#
# Check for our filter program
#
if type -p acroread &> /dev/null ; then
    pdftops=acroread
else
    test -x /usr/bin/pdf2ps || fault_filetype /usr/bin/pdf2ps
    pdftops=/usr/bin/pdf2ps
fi

#
# run the command on stdin
#
if type -p acroread &> /dev/null ; then
    medium="-size ${size:=a4}"
    case "${size:=a4}" in
	tabloid|11x17)		medium="-size tabloid" ;;
	a4dj)			medium="-size a4"      ;;
	letterdj)		medium="-size letter"  ;;
	letter|legal|ledger)	medium="-size $size"   ;;
	a[345)			medium="-size $size"   ;;
	b[45])			medium="-size $size"   ;;
    esac

    #
    # The current acroread crashes on reading from stdin
    #
    #   exec -a acroread acroread -toPostScript -level2 -shrink -expand -saveVM ${medium}

    trap 'test -n "$tmp" -a -e "$tmp" && rm -f "$tmp"
	  test -n "$out" -a -e "$out" && rm -f "$out"' EXIT
    tmp="$(mktemp ${TMPDIR:-/tmp}/lpdfilter-${0##*/}-XXXXXXXXXX)" || exit 2
    out="$(mktemp ${TMPDIR:-/tmp}/lpdfilter-${0##*/}-XXXXXXXXXX)" || exit 2
    cat > $tmp
    acroread -toPostScript -level2 -shrink -expand -saveVM ${medium} -pairs $tmp $out
    cat $out
else
    tmp="$(mktemp ${TMPDIR:-/tmp}/lpdfilter-${0##*/}.XXXXXXXXXX)" || exit 2
    cat > $tmp
    $pdftops -dPSLevel1 $tmp -
fi
