<?php

// Adapted from https://wiki.archlinux.org/index.php/Awstats

// Prepare environment

$newenv = $_SERVER;
$newenv["SCRIPT_FILENAME"] = $_SERVER["X_SCRIPT_FILENAME"];

if (!is_executable($_SERVER["X_SCRIPT_FILENAME"]) || is_dir($_SERVER["X_SCRIPT_FILENAME"]))
	error_exit(404, 'Not Found');

// Open process

$descriptorspec = array(
	array('pipe', 'r'),
	array('pipe', 'w'),
	array('pipe', 'w'),
);
$pipes = array();
$process = proc_open($_SERVER["X_SCRIPT_FILENAME"], $descriptorspec, $pipes, null, $newenv);

if (!is_resource($process))
	error_exit(500, 'Internal Server Error');

// All ok, send response

while (true) {
	$head = fgets($pipes[1]);
	if ($head === false || $head === "\r\n" || $head === "\n") break;
	header($head);
}
fpassthru($pipes[1]);

// Close

$scriptErrors = trim(stream_get_contents($pipes[2]));
foreach ($pipes as $fh) fclose($fh);
$returnValue = proc_close($process);
if ($scriptErrors) error_exit(500, "Status=$returnValue Error=$scriptErrors");
exit;

// Exit helper

function error_exit($code, $msg)
{
	header("$_SERVER[SERVER_PROTOCOL] $code $msg");
	echo($msg);
	trigger_error("$msg in $_SERVER[X_SCRIPT_FILENAME]", E_USER_ERROR);
	exit(1);
}