<?php

$id = $_REQUEST['id'];

$dirsize = 100;
$depth = 5;
$basedirs = array(
	'/usr/share/nginx/html/aio-replays',
);
$dirname = "";
$i = $depth;

while ($i > 1) {
      $dirname = $dirname . "/" . ($id/(pow($dirsize, ($i-1))))%$dirsize;
      $i = $i - 1;
}
$file = $dirname . "/" . $id . ".fafreplay";

foreach ($basedirs as $basedir) {
    if (is_readable($basedir . $file)) {
        $file = $basedir . $file;
        break;
    }
};

if (is_readable($file)) {
   header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
   header("Access-Control-Allow-Origin: *");
   header("Cache-Control: public"); // needed for i.e.
   header("Content-Type: application/octet-stream");
   header("Content-Transfer-Encoding: Binary");
   header("Content-Length:".filesize($file));
   header("Content-Disposition: attachment; filename=$id.fafreplay");
   readfile($file);
}
else {
   header($_SERVER["SERVER_PROTOCOL"] . " 404 NOT FOUND");
   header("Content-Type: text/plain");
   header("Access-Control-Allow-Origin: *");
   echo "Sorry, your replay was not found";
}
?>

