<?php
require "../.php/credentials.inc";
global $GITEA_TOKEN;

if ($_SERVER['PHP_AUTH_USER'] !== 'elwig' || $_SERVER['PHP_AUTH_PW'] !== 'ganzGeheim123!') {
    header('Status: 401');
    header('WWW-Authenticate: Basic realm="Elwig"');
    exit("401 Unauthorized :(\n");
}

$repo = "winzer/elwig-misc.git";
$url = "https://token:$GITEA_TOKEN@git.necronda.net/$repo";
$schema_version = $_GET['v'];

shell_exec("cd .repos; git clone $url; cd elwig-misc; git checkout main; git pull -f --rebase");

if ($schema_version) {
    $commit = shell_exec("cd .repos/elwig-misc; git log -p sql/v01/99.schema_version.sql | grep '+PRAGMA schema_version = ${schema_version}00;' -B 14 | head -n 1 | grep -oE '[^ ]+$'");
    if (!$commit) {
        header('Status: 404');
        exit("404 Specified schema version not found :(\n");
    }
    shell_exec("cd .repos/elwig-misc; git checkout $commit");
}

header('Content-Type: application/sql');
system("cd .repos/elwig-misc; cat \$(ls sql/*.*.sql sql/v01/*.*.sql | grep -vE -- '-fix|wb_gem' | awk -F'/' '{ print \$NF,\$0 }' | sort -t'/' -k1 -n | cut -f2- -d' ')");