<?php
/**
 * Lookup for _g() and _r() in php source code and build a gettext catalog (pot file)
 *
 * PHP 5.3
 *
 * @license MIT
 * @author Filip (transformation to build a gettext catalog)
 * @copyright 2014/02
 * based on extract2lang.php by author Romain d'Alverny, rdalverny, rda
*/

if (php_sapi_name() !== 'cli') {
    echo "CLI only.\n";
    exit(1);
}

if (version_compare(PHP_VERSION, '5.3.0') < 0) {
    echo "PHP 5.3 needed.\n";
    exit(1);
}

define('APP_ROOT', realpath(__DIR__ . '/..'));

$php_source = isset($argv[1]) ? $argv[1] : null;
$domain     = isset($argv[2]) ? $argv[2] : null;
$quiet      = isset($argv[3]) ? $argv[3] : false;

if (is_null($php_source) || is_null($domain)) {
    echo <<<U
Usage:
    php tools/extract2gettext.php path/to/source.php domain_name

    Example:
        php tools/extract2gettext.php en/index.php index

    You can join multiple sources with apostrophe - single quote (') like this:
        'en/3/download_index.php en/for-pc/index.php en/for-server/index.php en/3/index.php en/3/nav.php'

U;
    exit(1);
}

date_default_timezone_set(@date_default_timezone_get());

if(!$quiet) { echo "ohay!\n";}

$cmd = sprintf('grep -HrnE "_(g|r|t)\([^$](.*)" %s', $php_source);
if(!$quiet) { echo $cmd, "\n"; }
exec($cmd, $out);

$strings = array();
$f       = array();
$error   = 0;

if(count($out) == 0) {
    if(!$quiet) { echo "No strings to save from $php_source.\n"; }
    $error = 10;
}

foreach ($out as $str) {
    $arr     = explode(':', $str);
    $file    = array_shift($arr);
    $file    = str_replace(APP_ROOT, '', $file);
    $files[] = $file;
    $line    = array_shift($arr);
    $arr     = implode(':', $arr);
    $arr     = str_replace('\\\'', '_apostrophe_', $arr);

    if (preg_match_all('/\_(g|r|t)\(((\'(.+)\')|("(.+)"))/mU', $arr, $reg)) { // m=PCRE_MULTILINE, U=PCRE_UNGREEDY
        $results = array_merge($reg[4], $reg[6]);
        foreach ($results as $found) {
            if(!empty($found)) {
                $found = str_replace('_apostrophe_', '\'', $found);
                $strings[$domain][$found][] = '/web/' . $file . ' +' . $line;
            }
        }
    } else {
        $parse_error  = "\n\n!!!! Could not find string in $file, line $line: $str\n";
        $parse_error .= "!!!! Parse error, please fix $file before using $domain.pot file!!!\n\n";
        if(!$quiet) { echo $parse_error; }
        $error = 20;
    }
}

foreach ($strings as $domain => $strs) {
    $f[]     = '# gettext catalog for ' . $domain . ' web page(s)';
    $f[]     = '# Copyright (C) 2014 - ' . date('Y') . ' Mageia';
    $f[]     = '# This file is distributed under the same license as';
    $f[]     = '# the content of the corresponding web page(s).';
    $f[]     = '#';
    $cur_date = date('Y-m-d H:i:sO');
    $f[]     = '# Generated by extract2gettext.php';
    $f[]     = sprintf('# Domain: %s', $domain);
    $f[]     = '#';
    $f[]     = '# include translation strings from:';
    $files   = array_unique($files);
    foreach ($files as $source) {
        $f[] = sprintf('# %s', $source);
    }
    $f[]     = '#';
    $f[]     = 'msgid ""';
    $f[]     = 'msgstr ""';
    $f[]     = '"Project-Id-Version: ' . $domain . '\n"';
    $f[]     = '"Report-Msgid-Bugs-To: mageia-i18n@mageia.org\n"';
    $f[]     = '"POT-Creation-Date: ' . $cur_date . '\n"';
    $f[]     = '"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"';
    $f[]     = '"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"';
    $f[]     = '"Language-Team: LANGUAGE <LL@li.org>\n"';
    $f[]     = '"Language: \n"';
    $f[]     = '"MIME-Version: 1.0\n"';
    $f[]     = '"Content-Type: text/plain; charset=UTF-8\n"'; // CHARSET
    $f[]     = '"Content-Transfer-Encoding: 8bit\n"';
    $f[]     = '';

    foreach ($strs as $str => $info) {
        $str = str_replace(array("\'", '"'), array("'", '\"'), $str);
        $f[] = sprintf('#: "%s"', $info[0]); // location of string in the source (#: reference...)
        $f[] = 'msgid "' . $str . '"';
        $f[] = 'msgstr ""';
        $f[] = '';
    }
    $f = implode("\n", $f);
    if ($domain == 'mognase') {
        $dest = sprintf('%s/_nav/langs/en.pot', APP_ROOT);
    } else {
        $dest = sprintf('%s/langs/en/%s.pot', APP_ROOT, $domain);
    }
    $dir = dirname($dest);

    if (!is_dir($dir)) {
        if(!$quiet) { echo "making $dir\n"; }
        mkdir($dir, 0755, true);
    }
    if(!$quiet) { echo sprintf("saved %d strings in %s\n", count($strs), $dest); }
    if (FALSE === file_put_contents($dest, $f)) {
        if(!$quiet) { echo "Failed to write $f to $dest.\n"; }
        $error = 30;
    }
}
if(!$quiet) { echo "Done. thxbye.\n"; }
exit($error);