#!/usr/bin/env php
<?php
$queueDir = __DIR__ . "/../queue";
$queueDir = realpath($queueDir);
$queueItems = glob($queueDir . "/*.json");
$dlDir = __DIR__ . "/../html/dl/";
if (!is_dir($dlDir)) {
    mkdir($dlDir);
}
if (empty($queueItems)) {
    //clean up old files from dldir older than 24h
    $oldFiles = glob($dlDir . "/*.zip");
    foreach ($oldFiles as $oldFile) {
        if (filemtime($oldFile) < time() - 24 * 60 * 60) {
            unlink($oldFile);
        }
    }
    exit();
}
sort($queueItems);
$jobFile = array_shift($queueItems);
$jobId = basename($jobFile, ".json");
$tags = json_decode(file_get_contents($jobFile), true);
$zipFile = $dlDir . $jobId . ".zip";
chdir(__DIR__ . "/../AuerNameTag");
$shellArgs = array_map(function($tag){
    return escapeshellarg($tag['name'].' '.$tag['symbolPrefix'].' '.$tag['symbolPost']);
}, $tags);
system("rm -rf out");
system("git reset --hard");
system("./make.sh " . implode(" ", $shellArgs));
chdir("out");
system("zip -r $zipFile .");
chdir("..");
system("rm -rf out");
unlink($jobFile);

