#! /usr/bin/perl

# add a new text to *.po files

sub usage () {
  die "usage: add_text [-b id] [-c comment] id text_line1 text_line2 ... \nexample:\n  add_text MENU_LANG Language\n";
}

usage if @ARGV < 2;

my $before_id = '';
my $comment;

while ($ARGV[0] =~ /^-/) {
  if ($ARGV[0] eq '-b') {
    shift;
    $before_id = shift;
  } elsif ($ARGV[0] eq '-c') {
    shift;
    $comment = shift;
  } else {
    usage;
  }
}

$id = shift;
@texts = @ARGV;

$before_id =~ s/^txt_//;
$id =~ s/^txt_//;

$_ = join '', @texts;

push @l, "#. $comment\n" if $comment;
push @l, "#. txt_$id\n";
push @l, "#, c-format\n" if /%/;

if(@texts == 1) {
  push @l, "msgid \"$texts[0]\"\n"
}
else {
  push @l, "msgid \"\"\n";
  for (@texts) { push @l, "\"$_\"\n" }
}

push @l, "msgstr \"\"\n";

print @l;

print STDERR "Should this entry be added to all *.po files? [Y/n]\n";

$_ = <STDIN>;

chomp;

$_ = "\L$_";

exit unless $_ eq '' || $_ eq 'y';

print "ok\n";

for $f ("bootloader.pot", <*.po>) {
  open OLD, $f or next;
  unless (open NEW, '>', "$f.new") {
    close OLD;
    next;
  }
  my @buffer;
  for (<OLD>) {
    if ($before_id) {
      if (/^#\./) {
        push @buffer, $_;
        if (/^#\. txt_\Q$before_id\E$/) {
          print NEW @l, "\n";
          print NEW @buffer;
          @buffer = ();
        }
      } elsif (/^msgid/) {
        print NEW @buffer;
        @buffer = ();
        print NEW;
      } elsif (@buffer) {
        push @buffer, $_;
      } else {
        print NEW;
      }
    } else {
      print NEW;
    }
  }
  print NEW @buffer if @buffer;
  if (not $before_id) {
    print NEW "\n", @l;
  }
  close NEW;
  close OLD;
  rename "$f.new", $f;
}

