#!/bin/sh

# CUPS (Common Unix Printing System) filter to fix certain "broken" PostScript files

# The files generated by Hewlett-Packard's Windows drivers for the "LaserJet
# 5P/5MP PostScript" printer include a PJL header (that switches that printer
# to PostScript) before the actual PostScript file, and some weird additional
# comments within the PostScript.  If you are sending these files (via Samba)
# to a plain LaserJet 5P (i.e., without PostScript), you need to remove the
# header and the weird additional comments before sending the file to
# ghostscript.  Though it is a reasonable guess that the same situation applies
# to other pairs of HP printers with and without native PostScript
# capabilities, I have tested this script only with the LaserJet 5P.

# The garbage we are trimming at top and bottom of the file is fixed-length, so
# we could use something simpler than awk to trim it, but we have to use awk
# anyway to skip those weird comment lines (3d line of the program below), so
# let's just use awk for the whole thing.

# I wrote this awk script in the mid-1990s when I bought this printer, and it
# still serves me well today, with the latest versions of Windows, Debian, and
# Samba, and with CUPS instead of old BSD lpd and magicfilter.  I adapted it
# for CUPS in April 2004.  I put this code into the public domain.  I am not
# putting my name on it because I do not want to receive emails with questions
# about things I do not know much about.

# TODO
#   does the code here involve gawk extensions?

# on error, exit with this status.
CUPS_SAMBAPS_ERREXIT=2

prog=$(basename "$0")
# This statement needs bash I think.
echo "DEBUG: $prog: \"$0\" has been called with these arguments:" >&2
count=1
for x; do
    echo "DEBUG: $prog: arg $((count++)): \"$x\"" >&2
done

if ! shift 5; then
    echo "ERROR: $prog: expected 5 or 6 arguments and received <5" >&2
    exit $CUPS_SAMBAPS_ERREXIT
elif [ $# -gt 1 ]; then
    echo "ERROR: $prog: expected 5 or 6 arguments and received >6" >&2
    exit $CUPS_SAMBAPS_ERREXIT
fi

# variable `printme' starts as 0
/usr/bin/awk \
    '/^%\!PS-Adobe-/                           {printme = 1}
     /^%%EOF/                                  {print; printme = 0}
     /\(%%\[ ?(ProductName:|Page:|LastPage ?)/ {next}
                                               { if (printme) print; else next }' \
    ${1--}    
exit
