#!/usr/bin/perl
# Given a partial templates file on stdin which can contain some
# existing templates for countries, generates a complete templates file on
# stdout for all countries listed in the zone.tab. Also writes out the
# tzmap file, and uses tzmap.override to force countries that have only one
# zone. See README for details.

use warnings;
use strict;

my $iso3166tab = 'debian/iso_3166.tab';
my %country;
open (ISO, $iso3166tab) || die "$iso3166tab: $!";
while (<ISO>) {
	chomp;
	next unless length;
	my ($cc, $country)=split(/\t/, $_, 2);
	$country{$cc}=$country;
}

print ("#\n" x 10);
print "# This file was generated automatically, edit its source file instead\n";
print ("#\n" x 10);

sub honking_big_comment {
	my ($cc)=@_;
	my $country=exists($country{$cc}) ? $country{$cc} : $cc;
	return <<"EOF"
# Time zone for $country
EOF
}

my %seencc;
{
	local $/="\n\n";
	while (<>) {
		if (m!Template: tzsetup/country/([A-Z]+)!) {
			my $cc=$1;
			$seencc{$cc}=1;
			s/(__Choices:)/honking_big_comment($cc).$1/me;
		}
		print;
	}
}

my $zonetab="/usr/share/zoneinfo/zone.tab";
my %cc2zone;
my %zonedesc;
open (IN, $zonetab) || die "$zonetab: $!";
while (<IN>) {
	chomp;
	next if /^#/;
	next unless length;
	my ($cc, $coord, $zone, $comments)=split(' ', $_, 4);
	push @{$cc2zone{$cc}}, $zone unless $seencc{$cc};
	if (defined $comments) {
		$comments=~s/,/\\,/g; # escape for choices list
		$zonedesc{$zone}="$zone ($comments)"; 
	}
	else {
		$zonedesc{$zone}=$zone;
	}
}
close IN;

my %override;
open (OVERRIDE, "tzmap.override") || die "tzmap.override: $!";
while (<OVERRIDE>) {
	chomp;
	next if /^#/;
	my ($cc, $zone)=split(' ', $_, 2);
	$override{$cc}=1;
	$cc2zone{$cc}=[$zone];
}
close OVERRIDE;

open (TZMAP, ">debian/tzmap") || die "tzmap: $!";
foreach my $cc (sort keys %cc2zone) {
	my $list=join(", ", @{$cc2zone{$cc}});
	if (@{$cc2zone{$cc}} > 1 && ! $override{$cc}) {
		my $englist=join(", ", map { $zonedesc{$_} } @{$cc2zone{$cc}});
		print STDERR "warning: autogenerated template for $cc should be manually reviewed\n";
		print "\nTemplate: tzsetup/country/$cc\n";
		print "Type: select\n";
		print "Choices-C: $list\n";
		print honking_big_comment($cc);
		print "__Choices: $englist\n";
		print "Description: zone\n";
	}
	else {
		print TZMAP "$cc $list\n";
	}
}
close TZMAP;
