#!/bin/ksh
# I made this script to let me export papers to a PDF
# without the need for CUPS-PDF.
# This uses `enscript` and `ps2pdf` from Ghostscript,
# as well as the ubiquitous `file`.
# Note that I have aliased file to the GNU(?) version, as
# on illumos & OpenBSD the upstream `file` command
# does not support MIME-types.
alias file=/opt/local/bin/file
# Do whatever you want with this.
# -- operz@coralcmd.net

set -e

out_dir="$HOME/lp"
mkdir -p "$out_dir"

input=""
for arg in "$@"; do
    case "$arg" in
        -*) ;;  # skip dash
        *) input="${input:+$input }$arg" ;;  # preserve whitespace
    esac
done

tmpfile=$(mktemp /tmp/lprinput.XXXXXX)
if [[ -z "$input" ]]; then
        cat > "$tmpfile"
else
        cat $input > "$tmpfile"
fi

mime=$(file --mime-type -b "$tmpfile")

outfile="$out_dir/$(date '+%Y-%m-%d_%H-%M-%S').pdf"

case "$mime" in
  application/pdf)
    cp "$tmpfile" "$outfile"
    ;;
  application/postscript)
    ps2pdf "$tmpfile" "$outfile"
    ;;
  *)
    iconv -t iso-8859-1 "$tmpfile" | \
      enscript -q -e -o - 2>/dev/null | \
      ps2pdf - "$outfile"
    ;;
esac

rm -f "$tmpfile"
print "Saved PDF to $outfile"


