#!/usr/bin/perl
###############################################################################
#                                                                             #
# IPFire.org - A linux based firewall                                         #
# Copyright (C) 2026  IPFire Team  <info@ipfire.org>                          #
#                                                                             #
# This program is free software: you can redistribute it and/or modify        #
# it under the terms of the GNU General Public License as published by        #
# the Free Software Foundation, either version 3 of the License, or           #
# (at your option) any later version.                                         #
#                                                                             #
# This program is distributed in the hope that it will be useful,             #
# but WITHOUT ANY WARRANTY; without even the implied warranty of              #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               #
# GNU General Public License for more details.                                #
#                                                                             #
# You should have received a copy of the GNU General Public License           #
# along with this program.  If not, see <http://www.gnu.org/licenses/>.       #
#                                                                             #
###############################################################################
#
# Extracts all translatable strings of the web user interface into
# po/ipfire.pot and merges them into the translations in po/*.po.
#
# Strings are marked for translation by passing them to _(), optionally
# followed by a context:
#
#   print _('Hostname');
#   print "<td>@{[ _('Broken', 'vpn') ]}</td>";
#
# The arguments have to be string literals. xgettext does not find any calls
# in interpolated strings and here documents, so every source file is reduced
# to its calls, on the very same line, before it is passed on to xgettext.

use strict;

use Cwd;
use File::Basename;
use File::Find;
use File::Path;
use File::Temp;

my $basedir = cwd();
my $podir = "${basedir}/po";
my $domain = "ipfire";

# Where to search for translatable strings
my @searchpaths = (
	"config/cfgroot",
	"config/menu",
	"config/wio",
	"html/cgi-bin",
	"src/squid-accounting",
);

unless (-d $podir) {
	die "ERROR: Please run me from the top of the source tree!\n";
}

my $tmpdir = File::Temp->newdir();

# Find all files that have any translatable strings
my @files = ();

find({
	no_chdir => 1,
	wanted => sub {
		my $file = $File::Find::name;

		return unless (-f $file);

		push(@files, $file) if (&extract($file));
	},
}, @searchpaths);

@files = sort(@files);

# Create the template
my $pot = "${tmpdir}/${domain}.pot";

system("xgettext",
	"--language=Perl",
	"--from-code=UTF-8",
	"--keyword",
	"--keyword=_:1",
	"--keyword=_:1,2c",
	"--add-location=file",
	"--sort-by-file",
	"--package-name=IPFire",
	"--msgid-bugs-address=https://bugzilla.ipfire.org/",
	"--directory=${tmpdir}/src",
	"--output=${pot}",
	@files) == 0 or die "ERROR: xgettext failed\n";

# Only replace the template if more than its timestamp has changed
if (&read_template($pot) ne &read_template("${podir}/${domain}.pot")) {
	system("cp", $pot, "${podir}/${domain}.pot") == 0 or die "ERROR: Could not write the template\n";
}

# Update all translations
foreach my $po (sort glob("${podir}/*.po")) {
	system("msgmerge",
		"--quiet",
		"--update",
		"--backup=none",
		"--add-location=file",
		"--sort-by-file",
		$po, "${podir}/${domain}.pot") == 0 or die "ERROR: Could not update ${po}\n";

	# Check the translation
	system("msgfmt", "--check-format", "--output-file=/dev/null", $po) == 0 or die "ERROR: ${po} is broken\n";
}

exit 0;

#
# Writes all calls of _() in a file on their own and
# returns how many strings have been found
#
sub extract {
	my $file = shift;

	my $strings = 0;
	my $output = "";

	open(FILE, "<", $file) or die "ERROR: Could not open ${file}: $!\n";

	# A string literal
	my $string = qr/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/;

	while (my $line = <FILE>) {
		while ($line =~ m/(?<![\w\$\@%&])(?<!::)(?<!->)_\(\s*($string)\s*(?:,\s*($string)\s*)?\)/g) {
			if (defined $2) {
				$output .= "_(" . &literal($1) . ", " . &literal($2) . ");";
			} else {
				$output .= "_(" . &literal($1) . ");";
			}

			$strings++;
		}

		# Keep the line numbers
		$output .= "\n";
	}

	close(FILE);

	return 0 unless ($strings);

	&File::Path::make_path(dirname("${tmpdir}/src/${file}"));

	open(FILE, ">", "${tmpdir}/src/${file}") or die "ERROR: Could not write ${file}: $!\n";
	print FILE $output;
	close(FILE);

	return $strings;
}

sub literal {
	my $string = shift;

	# In an interpolated string, double quotes have to be escaped
	if ($string =~ m/^'/) {
		$string =~ s/\\"/"/g;
	}

	return $string;
}

sub read_template {
	my $file = shift;

	open(FILE, "<", $file) or return "";
	my @lines = grep { !/^"POT-Creation-Date: / } <FILE>;
	close(FILE);

	return join("", @lines);
}
