#!/usr/bin/perl
#
# handler: GPM (Gerald's Photo Metadata) handler
#
# Gerald Oskoboiny, 22 June 2000
#
# $Id: handler,v 1.3 2000/06/22 07:53:15 gerald Exp $
#

$ruri = $ENV{REQUEST_URI};

if ( $ruri eq $ENV{SCRIPT_NAME} ) {	# if called directly, show my source
    print "Content-Type: text/plain\n\n";
    open( SCRIPT, "< $ENV{SCRIPT_FILENAME}" ) or
        die "couldn't read myself because $!";
    while (<SCRIPT>) {
        print;
    }
    close( SCRIPT ) or warn "couldn't close myself because $!";
    exit;
}

my $gpmfile = $ENV{DOCUMENT_ROOT} . $ruri;

# does a GPM file exist for this (possibly generic) resource?
if ( ( ! -f $gpmfile ) && ( ! -f $gpmfile . ".gpm" ) ) {
    print "Status: 404 Not Found\n\n";
    exit;
}

if ( $gpmfile =~ /\.gpm$/ ) {	# GPM file explicitly requested; show it
    print "Content-Type: text/xml\n\n";
    open( GPMFILE, "< $gpmfile" ) or
        die "couldn't read gpmfile $gpmfile because $!";
    while (<GPMFILE>) {
        print;
    }
    close( GPMFILE ) or warn "couldn't close gpmfile $gpmfile because $!";
    exit;

}

# request was generic, so output a human-readable page with photo and metadata
$gpmfile .= ".gpm";

open( GPMFILE, "< $gpmfile" ) or
    warn "couldn't open gpmfile $gpmfile because $!";

print "Content-Type: text/html\n\n";
print "<title>photo metadata for $ruri</title>\n\n";

if ( -r $ENV{DOCUMENT_ROOT} . $ruri . "-med.jpg" ) {
    print qq{<p align=center><img src="$ruri-med.jpg"></p>\n};
}
elsif ( -r $ENV{DOCUMENT_ROOT} . $ruri . ".jpg" ) {
    print qq{<p align=center><img src="$ruri.jpg"></p>\n};
}

print "<p>\n  Image metadata:\n</p>\n\n";
print "<dl>\n";

while (<GPMFILE>) {
    next if /^<\/?gpm/;		# skip opening, closing elements
    ($name,$content) = (/^<([a-z]\w*)>(.*)<\/[a-z]\w*>$/);
    print "  <dt>\u$name<dd>$content\n";
}
print "</dl>\n\n";