<?php

$debug = 0;
include 'site.php';

// these are defined by site.php
// global $PERLLIB;
// global $BINDIR;
// global $SITE;

### these need to be set to the correct locations!!
$MISSING = "missing.png";

// load an image file from the image directory
// validate request
if ($_SERVER[REQUEST_METHOD] != 'GET') { 
  exit ();
}

putenv("PERL5LIB=$PERLLIB:");
$PATH = getenv("PATH");
putenv("PATH=$BINDIR:$PATH");

if ($debug) {
  echo "args: $args<br>";
  echo "path: $PATH<br>";
  echo "perl: $PERLLIB<br>";
  echo "bindir: $BINDIR<br>";
}

# $basename may contain filename@filerule
$basename = $_GET[name];
$filerule = $_GET[rule];
$camera   = $_GET[camera];
$class_id = $_GET[class_id];

# $filerule = strtok("@");

if ($debug) {
  echo "basename: $basename<br>";
  echo "filerule: $filerule<br>";
}

# need to supply the camera as well...

# if ($filerule) {
#   if ($filerule == "PPIMAGE.JPEG1") {
#     $basename = "$basename.b1.jpg";
#   }
#   if ($filerule == "PPIMAGE.JPEG2") {
#     $basename = "$basename.b2.jpg";
#   }
# }
# exec ("ipp_datapath.pl --site=$SITE $basename", $output, $status);

# do I need to do this to the output result as well?
$basename = escapeshellarg($basename);
$basename = str_replace ('..','',$basename);

if ($debug) {
  exec ("which ipp_filename.pl", $output, $status);
  echo "which ipp_filename.pl output:<br>";
  for ($i = 0; $i < count($output); $i++) {
    echo "output $i: $output[$i]<br>";
  }
  echo "status:   $status<br>";

  exec ("whoami", $output, $status);
  echo "which whoami output:<br>";
  for ($i = 0; $i < count($output); $i++) {
    echo "output $i: $output[$i]<br>";
  }
  echo "status:   $status<br>";
}

exec ("ipp_filename.pl --site=$SITE --basename $basename --filerule $filerule --camera $camera --class_id $class_id", $output, $status);

# use these to check the environment
# passthru ("env");
# passthru ("perl --version");

$filename = $output[0];
if ($status) {
  $filename = $MISSING;
}

if ($debug) {
  echo "basename: $basename<br>";
  for ($i = 0; $i < count($output); $i++) {
    echo "output $i: $output[$i]<br>";
  }
  echo "output:   $output[0]<br>";
  echo "status:   $status<br>";
  echo "filename: $filename<br>";
  exit ();
}

$file = fopen ($filename, "r");
if ($file && !$debug) {
  # do I need to use image/jpg? can I modify this to image/png, etc, based on the type?
  header ('Content-Type: image/jpg');
  fpassthru ($file);
}
exit ();
?>
