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

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || $_SERVER['PHP_AUTH_USER'] !== 'elwig' || $_SERVER['PHP_AUTH_PW'] !== 'ganzGeheim123!') {
    http_401_unauthorized('text');
}

$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 || !ctype_digit($schema_version)) {
    header('Status: 400');
    header('Content-Type: text/plain; charset=UTF-8');
    header('Content-Length: 16');
    exit("400 Bad Request\n");
} else {
    $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');
        header('Content-Type: text/plain; charset=UTF-8');
        header('Content-Length: 39');
        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' ')");
