#/bin/bash
# This script reads the cups-pdf configuration file specified and sets the
# options in the users lpoptions. Do not run this as root as it will set
# the options for all users (see man lpoptions)
# Usage: config2lpoptions <printer> <configfile>
#set -x

# check command line arguments
if [ $# -ne 2 ]; then
  echo Usage $0 \<printer\> \<config file\>
  exit 1
fi

if ! test -f $2; then
  echo Can not read config file $2
  exit -1
fi

PRINTER=$1
CONFIG_FILE=$2

process() {
  printer=$1
  text=$2

  # Strip all comments
  text=${text%%'#'*}

  # remove leading whitespace characters
  text="${text#"${text%%[![:space:]]*}"}"

  # remove trailing whitespace characters
  text="${text%"${text##*[![:space:]]}"}"

  #if remaining string is empty, we're done
  if [ -z "$text" ] ; then
    return
  fi

  set -- $text
  key=$1
  shift
  value=$*
  if [ -z "$value" ] ; then
    echo lpoptions -p $printer -o "$key"
    lpoptions -p $printer -o "$key"
  else
    value=`echo $value | sed -e 's/ /_/g' -e 's/"/\\"/g'`
    echo lpoptions -p $printer -o "${key}=${value}"
    lpoptions -p $printer -o "${key}=${value}"
  fi

}

a=0
while read line; do
  a=$(($a+1))
  process $PRINTER "$line";
  # echo $a;
done < $CONFIG_FILE
echo Done...
