#!/usr/bin/perl -w -T

my $loaded = 1;
use Apache::SubProcess qw(system exec);
use CGI;
use strict;
use Sys::Hostname;
use POSIX qw(tmpnam);

$ENV{PATH}="/bin:/usr/bin";
$ENV{ENV}="";

my $fileloc;
my %filemap;
if (hostname() eq "hugin.sabir.com") {
   $fileloc = "/mnt/pdp/";
   %filemap = (); 
} else {
   $fileloc = "";
   %filemap = ("webloc","/disk1/web-data/pdp8/",
               "newstuff","/disk1/home/djg/newstuff/"); 
}
my $tmpname = tmpnam();

        #$|=1;
	my $q=new CGI;
	#print $q->header();
	my $doc;
	$doc = $ENV{PATH_INFO};
	if (!defined($doc) || ($doc eq "")) {
	   $doc=$q->param('doc');
	} else {
	   $doc =~ s'\.pdf'.tif'
	}
#           print $q->header;
#           print "doc $doc\n";
	my $orig_doc = $doc;
	my $pages=$q->param('pages');
        if (defined($pages) && $pages =~ /^([0-9-]*)$/) {
           $pages = "--pages $1";
        } else {
           $pages = "";
        }
        if (defined($doc) && $doc =~ /^([0-9A-z-_^\/\.]*)$/) {
           $doc = $1;
        } else {
           $doc = '';
        }
        if ($doc =~ /\.\./) {
           $doc = '';
        }
	my $loc=$q->param('loc');
	if (defined($loc)) {
           $loc = $filemap{$loc};	
	   if (defined($loc)) {
	      $doc = $loc . $doc;
	   }
        }
        if ($doc eq '' || ! -e $fileloc.$doc) {
           print $q->header;
           print "File name $orig_doc:$doc not valid\n";
        } else {
           if (system("./c42pdf -q -o $tmpname -p o --nostretch --noflip $pages $fileloc$doc") != 0) {
              print "Conversion of file name $orig_doc:$doc failed\n";
           } else {
	      print $q->header(-type=>'application/pdf',-last_modified=>
                  set_last_mod_file("$fileloc$doc"),-content_length=>(stat ("$tmpname"))[7]);
              if ($loaded == 1) {
                 system "/bin/cat $tmpname";
              } else {
                 print `/bin/cat $tmpname`;
              }
              unlink($tmpname);
           }
        }

sub set_last_mod_file {
    my($file) = @_;

    my(@MON)=qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/;
    my(@WDAY) = qw/Sun Mon Tue Wed Thu Fri Sat/;

    my $time = (stat $file)[9];

    # make HTTP/cookie date string from GMT'ed time
    # (cookies use '-' as date separator, HTTP uses ' ')
    my($sc) = ' ';
    my($sec,$min,$hour,$mday,$mon,$year,$wday) = gmtime($time);
    $year += 1900;
    return sprintf("%s, %02d$sc%s$sc%04d %02d:%02d:%02d GMT",
                   $WDAY[$wday],$mday,$MON[$mon],$year,$hour,$min,$sec);
}

