#!/usr/bin/perl
use strict;

use File::Copy;
use Getopt::Std;
use POSIX;

# PACKAGE REQUIREMENTS:
# imagemagick unpaper sane-utils brscan2

# Specify scanner
my $scanner="brother2:net1;dev0";
# Set up path and file names
my $outputdir = "/home/scans";
my $stamp = POSIX::strftime( "%Y-%m-%d-%H%M%S", localtime());
my $dir = "/tmp/$stamp";
mkdir("$dir");
chdir("$dir");

# Options for copy, reduce
our($opt_c,$opt_r);
getopts( 'cr' );

print "Specified function: ";
my $yres = "279.4";
if ($opt_c) { print "COPY\n"; }
elsif ($opt_r) { 
    print "REDUCE\n";
    $yres = "355.6";
}
else { print "SCAN\n"; }

my @scancmd = ("scanimage", "-d", $scanner, "--mode", 
	       "Black & White", "--resolution", "300", "-x", 
	       "215.9", "-y", "$yres", "--batch=%03d.pbm");
print "Scanning with @scancmd\n";
system(@scancmd);

my @pbms = sort (<*.pbm>);

# Print with lpr if requested
for my $pbm (@pbms) {
    # pnmtops uses 300 dpi default; specify otherwise
    # The following line gives 1:1 on size, but adds printer margin cutoff
    # if ($opt_c) {system "pnmtops --equalpixels $pbm | lpr";}
    if ($opt_c) {system "pnmtops --imagewidth 8.0 $pbm | lpr";}
    if ($opt_r) {system "pnmtops --imageheight 10.5 $pbm | lpr";}
}

# Process PBMs
for my $pbm (@pbms) {
    # Process with unpaper
    system("unpaper", "--no-blackfilter", "--no-grayfilter", 
	   "--no-blurfilter", "--no-mask-center", "--no-border-scan",
	   $pbm, "unpaper_$pbm"); # --post-size letter shrinks
    rename("unpaper_$pbm", "$pbm");
}

# Generate PDF
system("convert", @pbms, "-alpha", "off", "-monochrome", "-compress",
       "Group4", "-quality", "100", "-units", "PixelsPerInch",
       "-density", "300", "$stamp.pdf");

#chown(1001, 1002, "$stamp.pdf");

move("$stamp.pdf", "$outputdir/${stamp}.pdf");
unlink(@pbms);
rmdir("$dir");

print "PDF saved as " . $stamp . ".pdf\n";
