#! /usr/bin/perl -w

use strict;
use File::Basename;
$| = 1;

print STDERR "# [WRAP] Called as ", join(" ", $0, @ARGV), "\n";

my $pwd = `pwd`;
chomp $pwd;
print STDERR "# [WRAP] Running in $pwd\n";

my $realitstool = shift @ARGV;

if (@ARGV > 2 && $ARGV[0] eq '-o' && $ARGV[1] =~ /\.pot$/) {
    &make_potfile();
} elsif (@ARGV > 2 && $ARGV[0] eq '-m' && $ARGV[1] =~ /\.mo$/) {
    &make_mofile();
} else {
    &fallback();
}

exit 0;

# -----------------------------------------------------------------------------

sub fallback {
    &run ($realitstool, @ARGV);
    &exit_if_failed ();
}

sub make_potfile {
    my ($dasho, $potfile, $main) = @ARGV;

    my $tmp = $main;
    $tmp =~ s/(\.xml)$/-tmp$1/;

    &run ("xmllint", "--noent", "-o", $tmp, $main);
    &exit_if_failed ();

    &run ($realitstool, $dasho, $potfile, $tmp);
    &exit_if_failed ();

    unlink $tmp;
}

sub make_mofile {
    my ($dashm, $mofile, $main) = @ARGV;

    my $rbuilddir = &dirname ($mofile);

    my $tmpbase = &basename ($main);
    $tmpbase =~ s/(\.xml)$/-tmp$1/;
    # The ".." here means "somewhere else" because intltool is weird
    my $tmp = "$rbuilddir/../$tmpbase";

    &run ("xmllint", "--noent", "-o", $tmp, $main);
    &exit_if_failed ();

    unlink ($tmpbase);
    &run ($realitstool, $dashm, $mofile, $tmp);
    &exit_if_failed ();
    &run ("mv", $tmpbase, &basename ($main));

    unlink $tmp;
}

# -----------------------------------------------------------------------------

sub run {
    my @cmd = @_;
    print STDERR "# [WRAP] Running ", join(" ", @cmd), "\n";
    system(@cmd);
}

sub exit_if_failed {
    return if $? == 0;
    print STDERR "# [WRAP] Failed, exit $?\n";
    exit 1;
}
