#!/bin/sh
#
# a2ps-lpr-wrapper - lp/lpr wrapper script for GNU a2ps

set -e

usage() {
  echo "Usage: $(basename "$0") [-d printer] [FILE...]" >&2
  exit 1
}

printer=""
while getopts d: flag; do
  case "$flag" in
    d) printer=$OPTARG ;;
    *) usage ;;
  esac
done
shift $((OPTIND - 1))

# If lp (from CUPS) exists, just use it.
if command -pv lp > /dev/null; then
  printer_opt=-d
  command="lp"
elif command -pv lpr >/dev/null; then
  # In case lp is not available, then fall back to lpr.
  printer_opt=-P
  command="lpr"
elif command -pv rlpr >/dev/null; then
  # In case lpr is not available, then fall back to rlpr.
  printer_opt=-P
  command="rlpr"
else
  # If none of lp, lpr and rlpr is available, then fail
  echo "$0: no program found to print files"
  exit 1
fi

# Run the command
opts=""
if [ "$printer" != "" ]; then
   opts="$printer_opt $printer"
fi
command -p "$command" $opts "$@"
