#!/usr/bin/perl
#
# This script works in conjunction with the tagger java classes.
# It writes image files to the server store and sends them back. 
# You need to set up the logdir with the path to the area you want the 
# images written to.
# Author: Tim Waters
# To do: Subr to send HTTP information: takes one argument, MIME type. prob not needed?

sub SendHeaders {
    my $mimetype = shift;
    print "Content-type: " . $mimetype . "\n\n";
    return;
}

$logdir = '/yourPathHere/logs/';

$PathInfo = $ENV{'PATH_INFO'};
$QueryString = $ENV{'QUERY_STRING'};
$ScriptURL = $ENV{'SCRIPT_NAME'};

if (!($ScriptURL)) {
    $ScriptURL = $ENV{'SCRIPT_URL'};
}

$CodeNumber = 0;
$mode = 5;
$FileName = "";

if ($QueryString =~ m/put[=-]([0-9a-f.]+)/) {
        $CodeNumber = $1;
        $mode = 2;
}

elsif ($QueryString =~ m/get[=-]([0-9a-z.]+)/) {
	
 	$FileName = $1;
	$mode = 3;
}
else {
        $mode = 5;
}

# Read GIF input from STDIN
# Variables that you use in a subroutine should be made private to that subroutine with the my operator.
# This avoids accidentally overwriting similarly-named variables in the main program.
# hence the my $buf

if ($mode == 2) {

$FileName = $logdir . $CodeNumber . ".gif";
open( GIF_FILE, ">" . "$FileName") || die "Cannot write $FileName: \n";

my $buf = "";
while (read (STDIN, $buf, $ENV{'CONTENT_LENGTH'}) ) {
 

# Write GIF input to a temporary file.
# Web users must have access to the directory where this file is written to.
# $gif_fname = "n".$ENV{'REMOTE_ADDR'} . "." . time() . ".gif" ;

binmode(GIF_FILE);
print GIF_FILE $buf;
} # end while

close GIF_FILE;

# send some stuff back in response
 SendHeaders("text/plain");
    print "Okay, accepted " . $FileName . "\n\n";
} # end if

elsif ($mode == 3) {

SendHeaders("text/plain");
    print "you asked for something! " . $FileName . "\n\n";
    
} # end else if


## if mode is 5 then exit

exit 0;


