<?
// cors.php by JB (wizard.ae.krakow.pl/~jb/)

$f = $_GET['file'];
if(!$f) {
	$f = substr($_SERVER['PATH_INFO'],1);
	if(!$f) err404();
}

if(preg_match('%^\.|/%',$f))
	err404();

if(!preg_match('/\.([a-zA-Z0-9]+)$/',$f,$m))
	err404();
$ext = $m[1];

$v = strtolower($ext);
switch($v) {
case 'z80':
case 'tap':
case 'scr':
case 'sna':
	$type = "application/x.zx.$v";
	break;
default:
	err404();
}

if(!file_exists($f))
	err404();

header("Content-Type: $type");
header('Access-Control-Allow-Origin: *');

$body = file_get_contents($f);
$l = strlen($body);

$etag = sprintf('"%s%x"', hash('crc32b',$body), $l);
header("Etag: $etag");

$v = $_SERVER['HTTP_IF_NONE_MATCH'];
if($v==$etag) {
	header('HTTP/1.1 304 Not Modified');
	exit;
}

echo $body;

function err404() {
	header('HTTP/1.1 404 Not Found');
	echo 'Not Found';
	exit;
}

?>