#!/bin/bash
# ASCII to PDF virtual printer (stdin)
#
# Usage: hpir TYPE ENCODING USER [TITLE]
#
#   -a  HP 82240A
#   -b  HP 82240B
#   -g  49/50G
#
# Note: when printing text after graphics from HP 28, send ESC + HP Roman 8 {27 248} before text.


PDF="/home/$(echo $3 | tr '[:upper:]' '[:lower:]')/$(date +%s).pdf"
GR="[-]"
TX="[]"
FT=""
CR="\004"


hp() {
    perl -pe "s/\r\n$//; /$GR/ && s/\n/\\\012/g"\
      | perl -pe "/$GR/ && s/$CR($GR)/\n\1/g; /$GR/ && s/$CR($TX)/\n\1/g; /$GR/ && s/$CR$CR($FT)/\n\n\1/; /$GR/ && s/$CR$/\n/"\
      | perl -pe "/$GR/ && s/$CR/\\\004/g; /$GR/ && s/\t/\\\011/g; /$GR/ && s/\f/\\\014/g; /$GR/ && s/\r/\\\015/g; s/$CR/ \n/g; s/$/ /"
}

genconhp() {
    a2ps -E$3 -X$4 -M$1 -T8 -1Bcl664 --borders=no --non-printable-format=octal --prologue=$2 -qo- - | ps2pdf -sPAPERSIZE=$1 - "$PDF"
}


case "$1" in
    -[ab])  hp | genconhp roll57 hp$1 hpir$1 $2;;
    -g)     hp | genconhp roll80 hp$1 hpir$1 $2;;
esac
chmod 644 "$PDF" && basename "$PDF"

