#!/usr/bin/perl -l
use warnings;
use strict;
use Getopt::Std;

use vars qw($LIB @scripts %opts $lang $debug $folder);

$folder = &get_debian_version();
#$LIB = '/usr/lib/localization-config/'.$folder;
$LIB = './conffiles.d/'.$folder;

@scripts = grep { $_ if -f $_ } glob "$LIB/*";

getopts("dlp", \%opts);

if ($opts{'l'}) {
    list_supported();
    exit 0;
}

if ($opts{'p'}) {
    debug("Running preinst scripts");
} else {
    debug("Running postinst scripts");
}

$lang = shift;

debug("Got langcode '$lang'\n");

die "Usage: $0 <language>\n" unless $lang;
die "$0: You must be root\n" if $>;

for my $script (@scripts) {
    if ($opts{'p'}) {
        if ($script =~ /.preinst$/) {
            debug("Running '$script $lang'\n");
	}
#    system ($script, $lang) if -x $script;
    }
}

sub debug {
    print @_ if $opts{'d'};
}

sub list_supported {
    my %locales;
    my %scriptsupport;
    for my $script (@scripts) {
    	if (-x $script) {
	    my @lines = `$script supported`;
	    chomp(@lines);
	    for my $locale (@lines) {
	        $locales{$locale} = 1;
		$scriptsupport{"$script:$locale"} = 1;
	    }
	}
    }
    print "Supported locales:";
    for my $locale (sort keys %locales) {
        print "  $locale";
	for my $script (sort @scripts) {
	    if ( ! exists $scriptsupport{"$script:$locale"}) {
		print "    Missing in $script";
	    }
	}
    }
}

# Will return the first correct supported Debian version
sub get_debian_version() {
    my %supported_versions = (	'woody'            => { FOLDER => 'woody' },
                                'sarge'            => { FOLDER => 'sarge' },
                                'testing/unstable' => { FOLDER => 'sarge' }
                             );
    my $debver_file= "/etc/debian_version";
    my $version, my $found, my $folder;
    open(DAT, $debver_file) || die("Could not open /etc/debian_version!");
    my @raw_data=<DAT>;
    close(DAT);
    foreach $version (@raw_data) {
        chop($version);
        if (defined($found = $supported_versions{$version})) {
        return $found->{'FOLDER'};
        }
    }
}
