#!/bin/bash
#
# nxprint - Prints a list of available drivers or printers
# 
# Copyright (c) 2005 by Fabian Franz <freenx@fabian-franz.de>
#
# License: GPL, version 2
#
# SVN: $Id: nxprint 405 2007-10-14 22:25:14Z fabianx $
#

HELP="no"
DRIVERS="no"
PRINTERS="no"

while [ "$1" ]
do
        case "$1" in
                --help) HELP="yes"; shift ;;
                --drivers|-d) DRIVERS="yes"; shift ;;
                --printers|-l) PRINTERS="yes"; shift ;;
                --) shift ; break ;;
                *) echo "Invalid flag $1" ; HELP="yes"; shift ; break ;;
        esac
done

[ "$DRIVERS" = "no" -a "$PRINTERS" = "no" ] && HELP="yes"

if [ "$HELP" = "yes" ]
then
        echo "nxprint - Prints a list of available drivers or printers"
	echo ""
        echo "Syntax: nxprint --help"
        echo "        nxprint --drivers"
        echo "        nxprint --printers"
        echo
        echo "  --drivers                prints a list of available CUPS drivers"
        echo "  --printers               prints a list of available CUPS printers"
        exit 0
fi

if [ "$DRIVERS" = "yes" ]
then
	echo "driver|Raw|Raw Queue|raw"
	echo "driver|Download (CUPS)|Download from CUPS server (cached)|download_cached"
	echo "driver|Download (CUPS)|Download from CUPS server (redownload)|download_new"
	#JJK: Added the following to avoid multiple calls to NXPRINT which are
	#JJK: *SLOW* when using 1500+ foomatic drivers
	#JJK: Note cache is reloaded after 60 minutes (or if empty)

	if [ -z "$(find $UTILITY_DRIVERS_CACHE.all -mmin -60 2> /dev/null)" ]
	then
		{ 
		cd /usr/share/ppd/
		awk -F '"' '/\*Manufacturer:/ { a[FILENAME]=$2 }
			    /\*NickName:/ { b[FILENAME]=$2 } 
			    END { 
			       for (i in a) 
				  print "driver|" (a[i]=="ESP"?substr(b[i],0,index(b[i]," ")-1):a[i]) "|"b[i]"|"i"|en"
			    }' $(find -name "*.ppd")

		if [ "$ENABLE_FOOMATIC" = "1" ]
		then
			[ -z "$COMMAND_FOOMATIC" ] && COMMAND_FOOMATIC="foomatic-ppdfile" 
			$COMMAND_FOOMATIC list | awk -F'"' '{ A=""; if ($4 == "HP") { B=substr($6,index($6," ")+1); A=" "substr(B,0,index(B," ")); } printf("driver|%s%s|%s|%s|%s\n",$4,A,$6,$2,substr($3,2)) } '
		fi
		} | sort > "$UTILITY_DRIVERS_CACHE".all
       fi

       cat "$UTILITY_DRIVERS_CACHE".all
fi

if [ "$PRINTERS" = "yes" ]
then
	lpstat -p | awk '{ print $1 "|" $2 }'
fi
