#!/bin/ash
# mu-lpr for muLinux
# [Use sed,tr, efix]

#set -x

if [ -r /setup/cnf/printer.cnf ] ; then
	. /setup/cnf/printer.cnf
else
	PRINTER=ascii
	RESOLUTION=300x300
	SCALE="0.9x0.9"
	DISPLACEMENT="0x0.4"
	PAGE=a4
fi

# parser

case $0 in
*/lpq|lpq|*/lprm|lprm)
	echo "No local spool supported."
	exit 0
	;;
esac

DEVICE=/dev/lp

case "$PAGE" in
letter)	FORMAT="8.465x11in";;
legal)	FORMAT="8.465x14in";;
A4|a4)	FORMAT="21x29.7cm";;
esac

#----------------------
# auxiliary functions
#----------------------

file_type()
{
read x 

        case $x in
        %!*)    echo "ps"
                ;;
        II*|MM*|P4)
                echo "image"
                ;;
        *)      echo "txt"	# !!!!
                ;;
        esac
}

abort()
{
>/dev/null; echo "aborted" >>/var/log/lp.log; exit 1
}

# Convert Unix->DOS: \n -> \r\n
2ascii()
{
cat "$@"| ( sed "s/%/#perc#/g; s/@/#amp#/g" |\
tr '\012' '%'|\
sed 's/%/@%/g' |\
tr '%' '\012' |\
tr '@' '\015' |\
sed "s/#perc#/%/g; s/#amp#/@/g"; echo -e \\f)
}

2ps()
{
efix -vei -ops -r"$RESOLUTION" -s"$SCALE" -d"$DISPLACEMENT" 
}

2pcl()
{
efix -vei -opcl -r"$RESOLUTION" -s"$SCALE" -d"$DISPLACEMENT"
}

2raw()
{
cat
}

# raw printer

txt2raw() { 2raw; } 
ps2raw() { 2raw; }
image2raw() { 2raw; }


# ascii printer

txt2ascii() { 2ascii; } 
ps2ascii() { abort; }
image2ascii() { abort; }

# ps printer

txt2ps() { 2ps; }
ps2ps() { cat; }
image2ps() { 2ps; };

# pcl printer

txt2pcl() { 2pcl; }
ps2pcl() { abort; }
pcl2pcl() { cat; }
image2pcl() { 2pcl; }

# Main
#----------------

# Syntax

case $1 in
-h)    	
cat <<END
mu-lpr, Usage : `basename $0` [-h] [-f output] [files] 
	
	This lpr support only ASCII and HP-PCL printers
	and work for fews file-type: TIFF-g3 (fax) and ascii.

END
exit
        ;;
-f)
	shift;
	DEVICE=$1
	shift
	;;
esac

input=/tmp/lpr-stdin.$$

case $# in
0|1)
	cat $1 > $input
	in=`cat $input| file_type`
	out=$PRINTER
	op="${in}2${out}"

	error="no error"

	echo " --- Attempt to print ${1:-stdin} ($op) ---" >>/var/log/lp.log
	echo -n "Printing ... "
	
	cat $input | eval $op > $DEVICE  2>>/var/log/lp.log
	[ $? -ne 0 ] && error="error: see /var/log/lp.log"
	;;

*)     
	for f in "$@"
	do
	$0 -f ${DEVICE} $f
	done
        ;;
esac

echo "Done $op ($error)"

# Done
