<?php
require "../.php/format.inc";
require "../.php/auth.inc";

$ua = $_SERVER['HTTP_USER_AGENT'] ?? null;;

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    authenticate(['PUT'], 'text');

    header('Content-Type: text/plain; charset=UTF-8');

    $name = substr($_SERVER['PATH_INFO'], 1);
    if (str_contains($name, "..") || str_contains($name, "/")) {
        header('Status: 403');
        header('Content-Length: 14');
        exit("403 Forbidden\n");
    } else if (!isset($_SERVER['HTTP_CONTENT_LENGTH'])) {
        header('Status: 411');
        header('Content-Length: 20');
        exit("411 Length Required\n");
    }

    $upload = fopen("php://input", "r");
    $fp = fopen("/tmp/upload-$name", "wb+");
    if (!$upload || !$fp) {
        fclose($fp);
        fclose($upload);
        header('Status: 500');
        header('Content-Length: 26');
        exit("500 Internal Server Error\n");
    }

    while ($data = fread($upload, 4096)) fwrite($fp, $data);
    fclose($fp);
    fclose($upload);

    if (!rename("/tmp/upload-$name", $name)) {
        header('Status: 500');
        header('Content-Length: 26');
        exit("500 Internal Server Error\n");
    }

    header('Status: 201');
    header('Content-Length: 12');
    exit("201 Created\n");
} else if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') {
    header('Status: 405');
    header('Allow: GET, HEAD, PUT');
    header('Content-Type: text/plain; charset=UTF-8');
    header('Content-Length: 23');
    exit("405 Method Not Allowed\n");
}

global $getProd;
global $getVers;
$getProd = null;
$getVers = null;
$info = explode('/', $_SERVER['PATH_INFO']);
if (sizeof($info) > 0 && $info[1] === 'stat') {
    header('Status: 303');
    header('Content-Length: 0');
    header('Location: /stat');
    exit();
} else if (sizeof($info) > 1 && ($info[1] === 'elwig' || $info[1] === 'winziprint' || $info[1] === 'pamhagen-sysctrl')) {
    $getProd = $info[1];
    if (sizeof($info) > 2 && !empty($info[2])) {
        $getVers = $info[2];
    }
    if (sizeof($info) > 3) {
        header('Status: 404');
        header('Content-Length: 0');
        exit();
    }
} else if ($_SERVER['PATH_INFO'] !== '') {
    header('Status: 404');
    header('Content-Length: 0');
    exit();
}

$filesRaw = scandir('.');
usort($filesRaw, 'version_compare');
$files = [];
foreach ($filesRaw as $file) {
    if (str_starts_with($file, ".") || str_ends_with($file, ".php") || !str_contains($file, ".")) continue;
    $files[$file] = [filesize($file), filemtime($file), filectime($file)];
}

$entities = [];
foreach ($files as $name => [$size, $mtime, $ctime]) {
    $p1 = strrpos($name, '-');
    $p2 = strrpos($name, '.');
    $url = "https://elwig.at/files/$name";
    if ($p1 === false || $p2 === false) {
        $vers = null;
        $prod = null;
    } else {
        $vers = substr($name, $p1 + 1, $p2 - $p1 - 1);
        $prod = strtolower(substr($name, 0, $p1));
        if ($prod === 'pamhagensysctrl') {
            $prod = 'pamhagen-sysctrl';
        }
    }
    $mod = date(DATE_ATOM, $mtime);
    $cre = date(DATE_ATOM, $ctime);
    $entities[$name] = [
        $prod,
        $vers,
        $url,
        $size,
        $mtime,
        $ctime,
        $mod,
        $cre
    ];
}

if ($getVers === 'latest') {
    $versions = [];
    foreach ($entities as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
        if ($prod === $getProd) $versions[] = $vers;
    }
    usort($versions, 'version_compare');
    $getVers = $versions[sizeof($versions) - 1];
}

$entities = array_filter($entities, function($e) {
    global $getProd;
    global $getVers;
    return (empty($getProd) || $getProd === $e[0]) && (empty($getVers) || $getVers === $e[1]);
});

$format = get_fmt();
file_put_contents('.log.csv', time() . "|$_SERVER[REMOTE_ADDR]|$_SERVER[REQUEST_METHOD]|$_SERVER[REQUEST_URI]|$format|$ua\n", FILE_APPEND);

if ($format === 'json') {
    header('Content-Type: application/json; charset=UTF-8');
    echo "{\"data\": [\n";
    $first = true;
    foreach ($entities as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
        if (!$first) echo ",\n";
        echo "  {\"product\": \"$prod\", \"version\": \"$vers\", \"name\": \"$name\", \"url\": \"$url\", \"size\": $size, \"created\": \"$cre\", \"modified\": \"$mod\"}";
        $first = false;
    }
    echo "\n]}\n";
} else if ($format === 'text') {
    header('Content-Type: text/plain; charset=UTF-8');
    foreach ($entities as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
        echo "$name\t" . number_format($size / 1024 / 1024, 1) . " MB\n";
    }
} else {
    if (isset($getProd) && isset($getVers) && sizeof($entities) === 1) {
        header('Status: 303');
        header('Location: ' . $entities[array_key_first($entities)][2]);
        header('Content-Length: 0');
        exit();
    }
    header('Content-Type: text/html; charset=UTF-8');
    ?>
<html lang="de" prefix="og: https://ogp.me/ns#">
<head>
  <meta charset="UTF-8"/>
  <title>Downloads - Elwig</title>
  <meta name="description" content="Elektronische Winzergenossenschaftsverwaltung"/>
  <link rel="icon" href="/favicon.ico" sizes="16x16 20x20 24x24 30x30 32x32 36x36 40x40 48x48 60x60 64x64 72x72 80x80 96x96 128x128 256x256"/>
  <link rel="stylesheet" href="/res/style.css"/>
  <meta name="viewport" content="width=device-width,initial-scale=1.0"/>
  <meta name="theme-color" content="#A040C0"/>
  <meta name="mobile-web-app-capable" content="yes"/>
  <meta name="apple-mobile-web-app-capable" content="yes"/>
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>
  <meta property="og:site_name" content="Elwig"/>
  <meta property="og:title" content="Downloads - Elwig"/>
  <meta property="og:description" content="Elektronische Winzergenossenschaftsverwaltung"/>
  <meta property="og:type" content="website"/>
  <meta property="og:url" content="https://elwig.at/files/"/>
  <meta property="og:image" content="https://elwig.at/res/images/preview.jpg"/>
  <meta property="og:image:type" content="image/jpeg"/>
  <meta property="og:image:width" content="1200"/>
  <meta property="og:image:height" content="630"/>
  <meta property="og:locale" content="de"/>
  <meta property="og:ttl" content="60"/>
  <meta name="twitter:card" content="summary_large_image"/>
</head>
<body>
  <main>
    <section>
      <h3>Downloads</h3>
      <p class="center"><a href="/">Startseite</a></p>
      <table>
        <thead><tr><th class="center">Name</th><th class="center">Größe</th><th class="center">Änderungsdatum</th></tr></thead>
        <tbody>
<?php foreach (array_reverse($entities) as $name => [$prod, $vers, $url, $size, $mtime, $ctime, $mod, $cre]) {
    echo "          <tr><td><a href=\"/files/$name\">$name</a></td><td style='text-align: right;'>" . number_format($size / 1024 / 1024, 1) . " MB</td><td>" . date('d.m.Y, H:i', $mtime) . "</td></tr>\n";
} ?>
        </tbody>
      </table>
      <p class="center"><a href="?format=json">JSON-Format</a></p>
    </section>
  </main>
</body>
</html>
<?php }
