#!/bin/sh
set -e

# LPRng print filter for Dymo LabelManager PC / PC-II
#
# Reads from stdin (only vertical PBM images), writes to stdout.
#
# Note: change defaults below to match your situation

# Z-options with "lpr -Pdymopbm -Zoption1,option2 -Zoption3"  etc.
#
# Recognized:
#
# i:<inktype>	: Ink type, 0 1 2 ... or "i:black-on-white" etc.  (also i=..)
# p:<papersize>	: Paper size, 0 1 2 ... or "p:12mm" etc.	  (also p=..)
#		  [but doesn't seem to matter]
# nomargins	: Don't pass through dypbmfixmargins
# toeof		: Read to EOF instead of looking at PBM header; only
#		  works with "nomargins".

# Suitable LPRng /etc/printcap entry:
#
# dymopbm|Dymo LabelManager PC-II .pbm format
#	:lp=/dev/usb/lp0........or whatever
#	:sd=/var/spool/lpd/%P
#	:mx#100
#	:sh
#	:if=/somewhere/......../lprng-filter
#	:done_jobs=0
#
# Then have spooldir auto-created with "checkpc -f"


#BINDIR=somewhere/dylol
BINDIR="`dirname "$0"`"

# Defaults:
#LABELBYTES=12		# LMPC
LABELBYTES=16		# LMPC2
PAPERSIZE=12mm		# doesn't seem to matter
INKTYPE=black-on-white

MARGINS=1
EOFOPT=""		# used UNquoted


# If not running from magicfilter, we need to extract -Z ourselves
if ! [ -n "$ZOPT" ] ; then
  ZOPT=""
  while true ; do
    [ "x$1" != "x${1#-Z}" ] && ZOPT="$ZOPT","${1#-Z}"    # (extra "," is okay)
    shift || break
  done
fi
#echo "$ZOPT" > /tmp/filtout ; exit


ZOPT1=,"$ZOPT",  # easy parsing

while [ -n "$ZOPT1" ] ; do
  ZOPTTHIS="${ZOPT1%%,*}"
  ZOPT1="${ZOPT1#*,}"

  case "$ZOPTTHIS" in
    "")		: ;;

    i[:=]?*)	INKTYPE="${ZOPTTHIS#i?}"
		;;

    p[:=]?*)	PAPERSIZE="${ZOPTTHIS#p?}"
		;;

    nomargins)	MARGINS=0
		;;

    toeof)	EOFOPT="-E"  # used UNquoted
		;;

    *)		echo "$0: Unknown Z-option "'"'"$ZOPTTHIS"'"' 1>&2
		exit 1
		;;
  esac
done


if [ "x$MARGINS" = "x1" ] ; then
  "$BINDIR"/dypbmfixmargins
else
  cat
fi |
  "$BINDIR"/pbm2lmpc -l "$LABELBYTES" -p "$PAPERSIZE" -i "$INKTYPE" -t $EOFOPT
