#!/usr/bin/perl
# This script configures XFree86 for LTSP in skolelinux.

use strict;
use warnings;

require '/usr/lib/localization-config/sarge/xfree86-kbd';

BEGIN {
    my @f = split(m%/%, $0); pop @f;
    push @INC, join("/", @f);
}

my %lang_map = get_lang_map();

my $debug = 0;

my $LTS_CONF = "/opt/ltsp/i386/etc/lts.conf";

# If no locale is given as argument, quit
my $lang = $ARGV[0] or die "No language given";

# Print the supported locale entries.
if ("supported" eq $lang) {
    for $lang (sort keys %lang_map) {
        print "$lang\n";
    }
    exit 0;
}

if ( ! -f $LTS_CONF ) {
    print STDERR "warning: ltsp-xfree86-kbd: Doing nothing, lts.conf is missing.\n" if $debug;
    exit 0;
}

# Udate lts.conf, replacing "XkbLayout" line.
if(defined(my $conf = $lang_map{$lang})) {
    my $layout = $conf->{'LAYOUT'};
    my $options = $conf->{'XKBOPTIONS'};
    open(CFG, "< $LTS_CONF") || die "Unable to read $LTS_CONF";
    my @lines = <CFG>;
    close(CFG);
    chomp @lines;
    @lines = map { if (m/^(\s*XkbLayout\s*=\s*)(.+)$/)
                   { "\"$1$layout\""; }
                   else { $_; }
               } @lines;
    # the following is disabled for now, since LTSP 3.0 does not
    # support this option.
    # @lines = map { if (m/^(\s*XkbOptions\s*=\s*)(.+)$/)
    #                { "\"$1$options\""; }
    #                else { $_; }
    #            } @lines;
    open(CFG, "> $LTS_CONF.new") || die "Unable to write $LTS_CONF.new.";
    print CFG join("\n",@lines, "") || die "Unable to write to $LTS_CONF.new.";
    close(CFG) || die "Unable to close $LTS_CONF.new.";
    rename("$LTS_CONF.new", $LTS_CONF) ||
        die "Unable to rename $LTS_CONF.new to $LTS_CONF."; 
} else {
    die "$0: No support for language '$lang'\n";
}
