#!/usr/bin/perl

# Read in all command line options

use Getopt::Std;
# Model, media Type, Resolution, Image type, Cartridge, Dithering, Port
# alignA, alignB, alignC, alignD, alignE, alignF
getopts("m:t:r:i:c:d:p:A:B:C:D:E:F:");

# Read the "-m" option to get the model

my $model = $opt_m;
if (!defined($model)) {die "Printer model not specified, use \"-m z22\", \"-m z23\", \"-m z32\", \"-m z33\", \"-m z52\", or \"-m z53\".\n"};

if (!($model =~ m/^[zZ][235][23]$/)) {die "Chosen model does not exist, use \"-m z22\", \"-m z23\", \"-m z32\", \"-m z33\", \"-m z52\", or \"-m z53\".\n"};

$model =~ tr/Z/z/;
$model =~ s/z22/z32/; # The Z22 and Z32 are compatible to each other
$model =~ s/z23/z33/; # The Z22 and Z32 use also the same driver

# === ADAPT THIS TO FIT TO YOUR ENVIRONMENT ===

my $lexmarkpath = "/usr/local/lexmark/$model/";
my $lexmarkconfig = "$model.conf";
my $ghostscript = "/usr/bin/foomatic-gswrapper";

# =============================================

# The paper size is stuffed into the PostScript file (it must be given
# this way for foomatic producing correct PPD files).

# Read out the paper size here

my $maxlines = 100;             # how many lines to examine?
my $more_stuff = 1;             # there is more stuff in stdin.
my $linect = 0;                 # how many lines have we examined?
my $papersizex= "612";	        # The default size is "Letter".
my $papersizey= "792";

do {
    my $line;
    if ($line=<STDIN>) {
        #if ($linect == 0) {
        #    # Line zero should be postscript leader
        #    die 'job does not start with Postscript %! thing'
        #        if $line !~ m/^%!/;
        #} else {
            if ($line =~ m!^\s*<<\s*/PageSize\s*\[\s*([0-9]*)\s*([0-9]*)\s*\]\s*/ImagingBBox\s*null\s*>>\s*setpagedevice\s*$!) {
        	$papersizex = $1;
        	$papersizey = $2;
	    }
        #}
        # Push the line onto the stack for later spitting up...
        push (@examined_stuff, $line);
        $linect++;
    } else {
        # EOF!
        $more_stuff = 0;
        print "EOF\n";
    }
} while (($linect < $maxlines) and $more_stuff);

# Get the number of the page size for the command line of the Lexmark driver

my @papersizes = ( ( 612, 792 ),   #Letter
                   ( 612, 1008 ),  #Legal
                   ( 516, 729 ),   #B5
                   ( 595, 842 ),   #A4
                   ( 522, 756 ),   #Executive
                   ( 421, 595 ),   #A5
                   ( 0, 0 ),       #Custom Banner (not retrivable)
                   ( 0, 0 ),       #Ohfhagaki (not retrivable)
                   ( 283, 420 ),   #Hagaki
                   ( 279, 540 ),   #Envelope Monarch
                   ( 279, 639 ),   #Envelope 9
                   ( 297, 684 ),   #Envelope 10
                   ( 312, 624 ),   #Envelope DL
                   ( 459, 649 ),   #Envelope C5
                   ( 323, 459 ),   #Envelope C6
                   ( 499, 709 ),   #Envelope B5
                   ( 0, 0 ),       #Envelope D5 (not retrivable)
                   ( 0, 0 ),       #Envelope 7 5 (not retrivable)
                   ( 288, 432 ),   #Index 4X6
                   ( 216, 360 ),   #Index 3X5
                   ( 0, 0 ),       #Banner A4
                   ( 0, 0 ) );     #Banner letter

my $i;
my $papersizeindex = 0; # Default is "Letter"
for ($i = 0; $i <= 42; $i += 2) {
    if (($papersizex > $papersizes[$i]-3) &&
        ($papersizex < $papersizes[$i]+3) &&
        ($papersizey > $papersizes[$i+1]-3) &&
        ($papersizey < $papersizes[$i+1]+3)) {
	$papersizeindex = $i / 2;
    }
}

# Add the options to the command line

# Page size
my $driveroptions = "--mediasize $papersizeindex";

# Media Type
my $mediatype = $opt_t;
if ((defined($mediatype)) && ($mediatype ne "default")) 
    {$driveroptions = "$driveroptions --mediatype $mediatype"};

# Resolution
my $resolution = $opt_r;
if ((defined($resolution)) && ($resolution ne "default")) 
    {$driveroptions = "$driveroptions --resolution $resolution"};

# Image Type
my $imagetype = $opt_i;
if ((defined($imagetype)) && ($imagetype ne "default")) 
    {$driveroptions = "$driveroptions --intent $imagetype"};

# Ink Type
my $inktype = $opt_c;
if ((defined($inktype)) && ($inktype ne "default")) 
    {$driveroptions = "$driveroptions --output $inktype"};

# Dithering
my $dither = $opt_d;
if ((defined($dither)) && ($dither ne "default")) 
    {$driveroptions = "$driveroptions --halftone $dither"};

# Port
my $port = $opt_p;
if (!(defined($port))) {die "Specification of the port where the printer is connected needed."};

# Head Alignment
my $align_a = $opt_A;
my $align_b = $opt_B;
my $align_c = $opt_C;
my $align_d = $opt_D;
my $align_e = $opt_E;
my $align_f = $opt_F;

if ((defined($align_a)) && (defined($align_b))) {
    $driveroptions = "$driveroptions --align $align_a,$align_b";
    if ((defined($align_c)) && (defined($align_d))) {
	$driveroptions = "$driveroptions,$align_c,$align_d";
	if ((defined($align_e)) && (defined($align_f))) {
	    $driveroptions = "$driveroptions,$align_e,$align_f";
	}
    }
}

my $cmdline = "| $ghostscript -dBATCH -dNOPAUSE -dSAFER -r600 -sDEVICE=ppmraw -sOutputFile=- - | $lexmarkpath$model --config $lexmarkconfig $driveroptions --dotcounts > $port";

# Print the job

open PRINTER, $cmdline or die "Could not run printing command line.";
print PRINTER @examined_stuff; # first 100 lines or so
if ($more_stuff) {
    while (<STDIN>) {
	print PRINTER $_;
    }
}
close PRINTER or die "error closing $driverh";

exit 0;
