#!/usr/bin/perl
# First attempt at automatic debconf po file updates from the DDTP.
# Joey Hess <joeyh@debian.org>, GPL
#
# Run this in the directory of your package.

use warnings;
use strict;

sub usage {
	print STDERR <<"EOF";
Usage: $0 [nbadh]
  -n, --new	Only download translations newer than what is in unstable.
  -b, --better	Overwrite existing translations if DDTP has more complete ones.
  -a, --all	Download even incomplete tranlations, overwriting existing.
  -d, --dry-run	Do not really download anything.
  -h, --help	Show this help text.

Default behavior is to download all complete tranlations, as well as any
incomplete translations that are not translated at all yet locally.
Files are downloaded to debian/po/<ll>.po

Note that some modes may cause loss of data if you have translations
from third parties. Do a dry run first!
EOF
	exit(1);
}

use Getopt::Long;
Getopt::Long::Configure("bundling");
my ($only_new, $all, $better, $dry_run);
GetOptions(
	"new|n" => \$only_new,
	"all|a" => \$all,
	"better|b" => \$better,
	"dry-run|d" => \$dry_run,
	"help|h" => \&usage,
) || usage();

my $src='';
open (CONTROL, "<debian/control") || die "open debian/control: $!\n";
while (<CONTROL>) {
	chomp;
	if (/^Source:\s*(.*)/) {
		$src=$1;
	}
}
close CONTROL;

if (! length $src) {
	die "unable to find source package name in debian/control\n";
}

open (LIST, "wget -O - --quiet http://ddtp.debian.org/debconf/source/$src |") ||
	die "wget: $!\n";
while (<LIST>) {
	if (/^\s*(\+)?\s*(\*)?\s*<\s*a\s*href="([^"]+)"\s*>([^\/]+)\/templates-([^.]+)\.po\s*<\/a>\s*(\d+)\/(\d+)\/(\d+)\s*(\d+)\/(\d+)/) {
		my ($file, $pkg, $ll, $trans_in_unstable, $trans_from_ddtp,
		    $total_in_unstable, $trans_texts, $total_texts) =
			($3, $4, $5, $6, $7, $8, $9, $10);
		my $updated = (defined $1);
		my $complete = (defined $2);

		next if $pkg ne $src; # unnecessary, probably with new source pages
		next if $trans_texts == 0;
		
		print "$ll.po:". ' ' x (8 - length $ll);

		my $pct = "(".int($trans_from_ddtp / $total_in_unstable * 100).
		          "% vs ".int($trans_in_unstable / $total_in_unstable * 100).
			  "%)";
		
		if ($only_new && ! $updated) {
			print "old\t\tskipping\t$pct\n";
			next;
		}
		if (! $complete && ! $all) {
			if ($better && $trans_from_ddtp > $trans_in_unstable) {
				print "better\tdownloading\t$pct\n";
			}
			elsif (-e "debian/po/$ll.po") {
				if (! $better) {
					print "exists\tskipping\t$pct\n";
				}
				else {
					print "worse\tskipping\t$pct\n";
				}
				next;
			}
			else {
				print "new\tdownloading\t$pct\n";
			}
		}
		else {
			print "complete\tdownloading\t$pct\n";
		}
		
		system ("wget --quiet -O debian/po/$ll.po http://ddtp.debian.org/$file")
			unless $dry_run;
	}
}
close LIST || die "wget close: $!\n";
