#!/usr/bin/env php
<?php

require __DIR__.'/../../src/init.php';

$commit_hash = null;
for ($i = 1; $i < $argc; $i++) {
    switch ($argv[$i]) {
        case '--commit-hash':
            $commit_hash = $argv[++$i] ?? usage('missing value for --commit-hash');
            break;

        default:
            usage("unknown option {$argv[$i]}");
    }
}

if (is_null($commit_hash))
    usage();

$hashes = [
    'commit_hash' => $commit_hash,
    'assets' => []
];

foreach (['ic', 'foreignone'] as $project) {
    foreach (['js', 'css'] as $type) {
        $dist_dir = APP_ROOT.'/public/'.$project.'/dist-'.$type;
        $entries = glob_recursive($dist_dir.'/*.'.$type);
        if (empty($entries)) {
            fwrite(STDERR, "warning: no files found in $dist_dir\n");
            continue;
        }
        foreach ($entries as $file) {
            $hashes['assets'][$project][$type.'/'.basename($file)] = [
                'integrity' => []
            ];
            foreach (\engine\skin\FeaturedSkin::RESOURCE_INTEGRITY_HASHES as $hash_type) {
                $hashes['assets'][$project][$type.'/'.basename($file)]['integrity'][$hash_type] = base64_encode(hash_file($hash_type, $file, true));
            }
        }
    }
}

echo "<?php\n\n";
echo "return ".var_export($hashes, true).";\n";

function usage(string $msg = ''): never  {
    if ($msg !== '')
        fwrite(STDERR, "error: {$msg}\n");
    $script = $GLOBALS['argv'][0];
    fwrite(STDERR, "usage: {$script} --commit-hash HASH\n");
    exit(1);
}

function glob_escape(string $pattern): string {
    if (str_contains($pattern, '[') || str_contains($pattern, ']')) {
        $placeholder = uniqid();
        $replaces = [$placeholder.'[', $placeholder.']', ];
        $pattern = str_replace( ['[', ']'], $replaces, $pattern);
        $pattern = str_replace( $replaces, ['[[]', '[]]'], $pattern);
    }
    return $pattern;
}

/**
 * Does not support flag GLOB_BRACE
 *
 * @param string $pattern
 * @param int $flags
 * @return array
 */
function glob_recursive(string $pattern, int $flags = 0): array {
    $files = glob(glob_escape($pattern), $flags);
    foreach (glob(glob_escape(dirname($pattern)).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
        $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
    }
    return $files;
}