#!/usr/bin/php -q
<?php
/**
 * Find translatable strings in Twig templates and the PHP library
 * and merge them into the English PO file.
 *
 * It should be invoked from the root of a SimpleSAMLphp installation
 * and can work on:
 * - A specific module name given on the command line
 * - The main product and the standard modules, when invoked with '--main'.
 *
 * It will search all Twig templates for occurrences of the trans()
 * function, and all PHP code under src/ for the noop() function.
 */
declare(strict_types=1);

use SimpleSAML\Module;
use SimpleSAML\Utils;
use Symfony\Component\Filesystem\Filesystem;

// This is the base directory of the SimpleSAMLphp installation
$baseDir = dirname(__FILE__, 2);

// Add library autoloader
require_once($baseDir . '/src/_autoload.php');

if($argc != 2) {
    echo "Usage: $argv[0] (<module>|--main)\n";
    exit(1);
}

if($argv[1] === '--main') {
    $modules = ['', 'core', 'admin', 'cron', 'exampleauth', 'multiauth', 'saml'];
} else {
    $modules = [$argv[1]];
}

$transUtils = new Utils\Translate();
$sysUtils = new Utils\System();
$filesystem = new Filesystem();

$tempDirBase = $sysUtils->getTempDir() . "/temptemplatestemp";
// Ensure no leftover from any previous invocation
$filesystem->remove($tempDirBase);

$outputSuffix = '/locales/en/LC_MESSAGES';


foreach($modules as $module) {
    $tempDir = $tempDirBase . "/" . $module;
    $transUtils->compileAllTemplates($module, $tempDir);
    $domain = $module ?: 'messages';

    $moduleDir = $baseDir . ($module === '' ? '' : '/modules/' . $module);
    $moduleSrcDir = $moduleDir . '/src/';
    $outputDir = $moduleDir . $outputSuffix;
    print `find $tempDir $moduleSrcDir -name \*.php | xargs xgettext --default-domain=$domain -p $outputDir --from-code=UTF-8 -j --omit-header --no-location -ktrans -knoop -L PHP`;
}

$filesystem->remove($tempDirBase);
// TODO: merge new strings into translated languages catalogs
