#! /usr/bin/perl
$0 =~ m!^(.*)/[^/]+$!;
my $programpath = $1;
my $printcommand = '/usr/bin/lpr -P ';
my $egrep = '/bin/egrep';
my $cat = '/bin/cat';
my $cut = '/usr/bin/cut';
my $head = '/usr/bin/head';
my $tail = '/usr/bin/tail';
my $wc = '/usr/bin/wc';
my $adjustmentpagename = 'align.ps';
my $adjustmentpagepath = ($programpath ? "${programpath}:" : "") . '.:~:/usr/share/alignmargins:/usr/local/share/alignmargins:/usr/share:/usr/local/share:/usr/share/printer-testpages:/usr/local/share/printer-testpages:/usr/share/ghostscript/*/lib:/usr/local/share/ghostscript/*/lib';
my $ppddir = '/etc/cups/ppd';
my $printerconffile = '/etc/cups/printers.conf';

# Find "ćlign.ps"

my $adjustmentpage;
for $path (split(":", $adjustmentpagepath)) {
    if (-r "$path/$adjustmentpagename") {
	$adjustmentpage = "$path/$adjustmentpagename";
	last;
    }
}

# Are we running as root?

if (!(-w $printerconffile)) {die "\"alignmargins\" must be run logged in as \"root\"!";}

# Check whether there are local printer queues 

open NUMBEROFQUEUES, "$cat $printerconffile | $egrep '<Printer|<DefaultPrinter' | $wc -l |" or die "Cannot read local printer configuration!";
 
my $nqueues = <NUMBEROFQUEUES>;
close NUMBEROFQUEUES;

# Ask the user which printer he wants to align

print "\n";
print "CUPS printer margin and offset alignment\n";
print "----------------------------------------\n";
print "\n";
print "(C) 2001 by Till Kamppeter\n";
print "Free software under the terms of the GNU General Public License (GPL)\n";
my $queue = "";

do {
  print "\n";
  print "With this program you can adjust the margins and the position of the\n";
  print "printed contents on the paper. This way you get well-centered printouts and\n";
  print "you can make use of the whole imageable area of your printer, The driver\n";
  print "settings are overridden when this adjustment is used.\n";
  print "\n";
  print "This is especially important when your printer is used with a driver for\n";
  print "another printer to which yours is compatible (for example many laser\n";
  print "printers are compatible to the HP LaserJet printers). Your printer prints\n";
  print "with this driver, but the non-printable margins are usually different or the\n";
  print "contents is even not centered. With this program you can fix these problems\n";
  print "\n";
  print "The program can only be applied to local printer queues. The following\n";
  print "queues are available:\n";
  print "\n";

  system "$cat $printerconffile | $egrep '<Printer|<DefaultPrinter' | $cut -d ' ' -f 2 | $cut -d '>' -f 1 | $cat -n";

  print "\n";
  print "Please enter the number of the desired printer and make sure that it is\n";
  print "connected to your computer and turned on.\n";
  print "\n";

  print "Number: ";
  my $input = <STDIN>;

  if ( $input =~ m/^\s*(\d+)\D*/ ) {
    my $number = $1;
    if (($number > 0) && ($number <= $nqueues)) {
      open QUEUE, "$cat $printerconffile | $egrep '<Printer|<DefaultPrinter' | $cut -d ' ' -f 2 | $cut -d '>' -f 1| $head -$number | $tail -1 |";
      if (!$?) {
        $queue = <QUEUE>; 
        close QUEUE;
      }
    }
  } else {
    print "\nWrong input, try again!\n";
  }
} until ($queue ne "");

chomp $queue;

print "\n";
print "Printing margin/offset adjustment page ...\n";
print "\n";

# The "%!" which is needed in a file to be recognized as a PostScript file
# is missing in the adjustment page, therefore it is preceeded to the file
# here.
if (system "(echo %!; $cat $adjustmentpage) | $printcommand$queue") {
die "Could not print the adjustment page.";
}

print "Please read the instructions on the margin adjustment page and determine the\n";
print "six numbers mentioned there. If you measure in cm and not in inches, devide\n";
print "the measured quantities by 2.54 before you insert them into the equations\n";
print "shown on the page. You do not need to create any file with PostScript\n";
print "commands, this program will insert your settings into your printer's\n";
print "configuration.\n";
print "\n";
print "If the adjustment page did not come out of your printer, this method cannot\n";
print "be applied, press Ctrl + C to stop this program. This can especially happen\n";
print "with very old PostScript printers.\n";
print "\n";
print "Note also that this adjustment does not necessarily work with every driver.\n";
print "The concept is taken from GhostScript and the implementation of this program\n";
print "is not much tested yet.\n";
print "\n";

print "Please enter your results now:\n";
print "\n";

my $ml = 9999999.;
my $mb = 9999999.;
my $mr = 9999999.;
my $mt = 9999999.;
my $x = 9999999.;
my $y = 9999999.;

do {
  print "ml: ";
  my $input = <STDIN>;

  if ( $input =~ m/^\s*([+-]?[\d\.]+)\D*/ ) {
    my $number = $1;
    if (($number >= -100000) && ($number <= 100000)) {
      $ml = $number * 1.;
    }
  } else {
    print "Wrong input, try again!\n";
  }
} until ($ml != 9999999.);

do {
  print "mb: ";
  my $input = <STDIN>;

  if ( $input =~ m/^\s*([+-]?[\d\.]+)\D*/ ) {
    my $number = $1;
    if (($number >= -100000) && ($number <= 100000)) {
      $mb = $number * 1.;
    }
  } else {
    print "Wrong input, try again!\n";
  }
} until ($mb != 9999999.);

do {
  print "mr: ";
  my $input = <STDIN>;

  if ( $input =~ m/^\s*([+-]?[\d\.]+)\D*/ ) {
    my $number = $1;
    if (($number >= -100000) && ($number <= 100000)) {
      $mr = $number * 1.;
    }
  } else {
    print "Wrong input, try again!\n";
  }
} until ($mr != 9999999.);

do {
  print "mt: ";
  my $input = <STDIN>;

  if ( $input =~ m/^\s*([+-]?[\d\.]+)\D*/ ) {
    my $number = $1;
    if (($number >= -100000) && ($number <= 100000)) {
      $mt = $number * 1.;
    }
  } else {
    print "Wrong input, try again!\n";
  }
} until ($mt != 9999999.);

do {
  print "x: ";
  my $input = <STDIN>;

  if ( $input =~ m/^\s*([+-]?[\d\.]+)\D*/ ) {
    my $number = $1;
    if (($number >= -100000) && ($number <= 100000)) {
      $x = $number * 1.;
    }
  } else {
    print "Wrong input, try again!\n";
  }
} until ($x != 9999999.);

do {
  print "y: ";
  my $input = <STDIN>;

  if ( $input =~ m/^\s*([+-]?[\d\.]+)\D*/ ) {
    my $number = $1;
    if (($number >= -100000) && ($number <= 100000)) {
      $y = $number * 1.;
    }
  } else {
    print "Wrong input, try again!\n";
  }
} until ($y != 9999999.);

my $ppdfilename = "$ppddir/$queue.ppd";
print "\n";
print "Saving your settings in $ppdfilename ...\n";
print "\n";

my @marginsoption = (
  "*OpenUI *Margins/Page Margins/Offsets: PickOne\n",
  "*DefaultMargins: Custom\n",
  "*Margins Default/Driver Default: \"\"\n",
  "*Margins Custom/Custom (set with 'alignmargins'): \"<</.HWMargins[$ml $mb $mr $mt] /Margins[$x $y]>>setpagedevice\"\n",
  "*CloseUI: *Margins\n"
);

# Read PPD file of the chosen printer
 
if (!(-f $ppdfilename)) {die "No PPD file $ppdfilename!"};
open PPDFILE, "$ppdfilename" or die "Can't open $ppdfilename!";
my @ppdfile = <PPDFILE>;
close PPDFILE;

# Remove an old margin adjustment option

($_ =~ m!^\s*\*OpenUI\s*\*Margins/.*:! and $_="") foreach @ppdfile;
($_ =~ m!^\s*\*DefaultMargins:! and $_="") foreach @ppdfile;
($_ =~ m!^\s*\*Margins\s*.*/.*:! and $_="") foreach @ppdfile;
($_ =~ m!^\s*\*CloseUI:\s*\*Margins! and $_="") foreach @ppdfile;

# Insert the new margin adjustment option

splice(@ppdfile,-1,0,@marginsoption);

# Write back PPD file

open PPDFILE, ">$ppdfilename" or die "Can't open $ppdfilename";
print PPDFILE @ppdfile;
close PPDFILE;

# Re-initialize CUPS (must be done after a "manual" change on the PPD file)

system("killall -HUP cupsd");

print "\n";
print "Done.\n";
print "\n";
print "Now your printer \"$queue\" will use the new margin and offset settings by\n";
print "default. You can turn them off by switching the option \"Page Margins/Offsets\"\n";
print "to \"Driver Default\" in kprinter, GTKlp, or XPP.\n";
print "\n";
print "On the command line (\"lpr\", \"lp\", \"lpoptions\", ...) use the option\n";
print "\"-o Margins=Default\" to turn off and \"-o Margins=Custom\" to turn on your\n";
print "settings.\n";
print "\n";

exit 0;