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

require __DIR__.'/../../src/init.php';
global $config;

// Check if yaml extension is available
if (!function_exists('yaml_parse_file')) {
    fwrite(STDERR, "error: yaml extension is not installed. Please install php-yaml extension.\n");
    exit(1);
}

$commit_hash = null;
$app_root = null;
$changed_projects = [];
$config_file = null;

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

        case '--app-root':
            $app_root = $argv[++$i] ?? usage('missing value for --app-root');
            break;

        case '--changed-projects':
            $changed_projects_str = $argv[++$i] ?? usage('missing value for --changed-projects');
            $changed_projects = explode(' ', trim($changed_projects_str));
            break;

        case '--config-file':
            $config_file = $argv[++$i] ?? usage('missing value for --config-file');
            break;

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

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

$all_projects = $config['projects'];

// Load existing config if available
$hashes = [
    'commit_hash' => $commit_hash,
    'assets' => []
];

if (!empty($config_file) && file_exists($config_file)) {
    $existing_hashes = include $config_file;
    if (is_array($existing_hashes) && isset($existing_hashes['assets'])) {
        $hashes['assets'] = $existing_hashes['assets'];
    }
}

// Process only changed projects or all if none specified
$projects = !empty($changed_projects) ? $changed_projects : $all_projects;

foreach ($projects 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) {
            $asset_key = $type.'/'.basename($file);
            $hashes['assets'][$project][$asset_key] = [
                'integrity' => []
            ];
            foreach (\engine\skin\FeaturedSkin::RESOURCE_INTEGRITY_HASHES as $hash_type) {
                $hashes['assets'][$project][$asset_key]['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 --app-root APP_ROOT [--changed-projects PROJECTS] [--config-file FILE]\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;
}
