#!/usr/bin/perl
# Copyright (c) 2002 SuSE GmbH Nuernberg, Germany.  All rights reserved.
#
# Author: Marcus Schaefer <sax@suse.de>, 2002
# script: get console -> x11 xkb mapping information
# --
# CVS ID:
# --------
# Status: Up-to-date
#
use strict;

#=================================
# Globals...
#---------------------------------
my $CFGMap = "/usr/share/systemd/kbd-model-map";
my $CFGMap2 = "/usr/share/systemd/kbd-model-map.xkb-generated";

#=================================
# The magic main :-)
#---------------------------------
sub main {
#------------------------------------------------
# check for all the keyboard information needed
# to setup X11 XKB keyboard:
# --
	my $XkbVariant;
	my $XkbLayout;
	my $XkbModel;
	my $XkbOptions;
	my $Apply;

	my %map;
	my %map2;
	my %opt;

	if (! defined $ARGV[0]) {
		die "xkbctrl: no console name given";
	}
	if ($ARGV[0] =~ /(.*)\.map\.gz.*/) {
		$ARGV[0] = $1;
	}
	%map = ReadDataConfigMap ($CFGMap);
	%map2 = ReadDataConfigMap ($CFGMap2);
	%map = (%map, %map2);

	foreach (sort keys %map) {
	if ($_ eq $ARGV[0]) {
		my @list = split (/:/,$map{$_});
		$XkbLayout   = Tr (shift(@list));
		$XkbModel    = Tr (shift(@list));
		$XkbVariant  = Tr (shift(@list));
		$XkbOptions  = Tr (join(":",@list));
	}
	}
	$opt{-layout}  = $XkbLayout;
	$opt{-model}   = $XkbModel;
	$opt{-variant} = $XkbVariant;
	$opt{-option}  = $XkbOptions;
	foreach (sort keys %opt) {
	if (($opt{$_} ne "-") && ($opt{$_} ne "")) {
		$Apply = "$Apply $_ $opt{$_}";
	}
	}
	$Apply =~ s/^ +//;

	print "\$[\n";
	if ($XkbVariant ne "-") {
	print "   \"XkbVariant\"   : \"$XkbVariant\",\n";
	}
	print "   \"XkbLayout\"    : \"$XkbLayout\",\n";
	print "   \"XkbModel\"     : \"$XkbModel\",\n";
	if ($XkbOptions ne "-") {
	print "   \"XkbOptions\"   : \"$XkbOptions\",\n";
	}
	print "   \"Apply\"        : \"$Apply\"\n";
	print "]\n"
}

#----[ ReadDataConfigMap ]----------#
sub ReadDataConfigMap {
#--------------------------------------------
# read Keyboard.map information file...
# return a hash
#
	my $filename = $_[0];

	my $consoleName;
	my $stuff;
	my %result;

	if (! open (DATA,$filename)) {
		die "could not open file: $filename";
	}
	while (my $line=<DATA>) {
		$line =~ s/[ \t]+/:/g;
		chomp ($line);
		my @list = split (/:/,$line);
		$consoleName = shift (@list);
		$consoleName =~ s/ +//g;
		$consoleName =~ s/\t+//g;
		$stuff = join(":",@list);
		$result{$consoleName} = $stuff;
	}
	return (%result);
}

#---[ tr ]----#
sub Tr {
#----------------------------------------------
# translate item into a non whitespace format
#
	my $item = $_[0];
	$item =~ s/^\t+//g; $item =~ s/\t+$//g;
	$item =~ s/^ +//g; $item =~ s/ +$//g;
	return ($item);
}

main();
