#!/usr/bin/perl -w
use strict;
use v5.012;
$|=1;

# get list of scanners
my %scanners;
foreach(split(/\n/, `scanimage -L`)) {
	chomp;
	$scanners{$1}=$2 if(/device \`(.*)\' is a (.*)$/);
}

if(!$ENV{QUERY_STRING}) {
	# no query string
	print 
	"Content-Type: text/html\r\n\r\n".
	"<html><head><title>Scanner</title></head><body>".
        "<h1>Scanner</h1>".
	"<form action=\"/cgi-bin/scan.pl\" method=\"get\">";

	if(keys %scanners) {
		say "<table border=\"1\"><tr>";
		say "<th>Scanners:</th>";
		say "<td><select name=\"device\">";
		say "<option value=\"$_\">$scanners{$_}</option>"
			foreach(sort keys %scanners);
		say "</select></td></tr>";

		say "<tr><th>File Format:</th><td>";
		say "<input type=\"radio\" name=\"format\" ".
			"value=\"tiff\" checked=\"checked\">TIFF</input>";
		say "<input type=\"radio\" name=\"format\" value=\"pnm\">PNM</input>";
		say "</td></tr>";

		say "<tr><th>Mode:</th><td>";
		say "<input type=\"radio\" name=\"mode\" ".
			"value=\"Lineart\">Black & White</input>";
		say "<input type=\"radio\" name=\"mode\" ".
			"value=\"Gray\">Grayscale</input>";
		say "<input type=\"radio\" name=\"mode\" ".
			"value=\"Color\" checked=\"checked\">Color</input>";

		say "<tr><td colspan=\"2\" align=\"center\">";
		say "<input type=\"submit\" value=\"Do Scan!\"><br>";
		say "Please wait after clicking!</td></tr>";

	} else {
		print "<b>No available scanner found.</b><br>";
		print "Note: May be busy. Try again later.<br>";
		print "Note: May have crashed. Try re-plugging.<br>";
	}

	print
	"</form></body></html>";
} else {
	my (%params, @args);

	# parse parameter list
	foreach(split(/\&/, $ENV{QUERY_STRING})) {
		my ($k, $v) = split(/=/, $_, 2);
		$v =~ s/%3A/:/g if($k eq 'device');
		$params{$k}=$v;
	}

	# generate command line arguments
	push(@args, "--device=$params{device}") if($params{device});
	push(@args, "--format=$params{format}")
		if($params{format} eq 'tiff' || $params{format} eq 'pnm');
	push(@args, "--mode=$params{mode}")
		if($params{mode} eq 'Lineart' || $params{mode} eq 'Gray' ||
			$params{mode} eq 'Color');

#	print "Content-Type: text/plain\r\n\r\n";
#	say "$_ = $ENV{$_}" foreach(sort keys %ENV);
#	say "==========\nParams:";
#	say "$_ = $params{$_}" foreach(sort keys %params);
#	say "==========\nCommand:";
#	say "scanimage @args";

	# print header
	print "Content-Type: image/$params{format}\r\n";
	print "Content-Disposition: inline; filename=\"scan.$params{format}\"";
	print "\r\n\r\n";

	# print data (probably insecure)
	print `scanimage @args 2>/dev/null`;
}

