#!/bin/sh -e

PROG="${0##*/}" #program name

x11_config=/etc/X11/XF86Config-4
kbd_config=/etc/sysconfig/kbd
keys_list=/usr/share/predator/x11keys

[ -s "$kbd_config" ] && . "$kbd_config"

print_version()
{
	cat <<EOF
$PROG version 0.0.1

Written by Stanislav Ievlev

Copyright (C) 2004 ALT Linux Team
EOF
	exit
}

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG [options]

utility to apply X11 keyboard layout according current global system settings

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information

Report bugs to <inger@altlinux.org>
EOF
	[ -n "$1" ] && exit "$1" || exit
}


TEMP=`getopt -n $PROG -o h,v -l help,version -- "$@"` || print_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done

layout=${LAYOUT##.=}

#echo "LAYOUT=$layout"

xkb_layout=$(cat $keys_list|grep "^$layout[[:space:]]"|cut -f2)
xkb_options=$(cat $keys_list|grep "^$layout[[:space:]]"|cut -f3)
[ "$xkb_options" = "undef" ] && xkb_options=""
xkb_variant=$(cat $keys_list|grep "^$layout[[:space:]]"|cut -f4)
[ "$xkb_variant" = "undef" ] && xkb_variant=""

#echo "layout=$xkb_layout, options=$xkb_options, variant=$xkb_variant"

#update XKB values in config
#note: It's very simple version, you may have a problems if your use two Input devices with XKB settings
sed -r -i "s|([[:space:]]*)Option.*XkbLayout.*|\1Option \"XkbLayout\" \"$xkb_layout\"|" $x11_config
sed -r -i "s|([[:space:]]*)Option.*XkbOptions.*|\1Option \"XkbOptions\" \"$xkb_options\"|" $x11_config
sed -r -i "s|([[:space:]]*)Option.*XkbVariant.*|\1Option \"XkbVariant\" \"$xkb_variant\"|" $x11_config

#string for setxkbmap
echo setxkbmap -layout \"$xkb_layout\" -option \"$xkb_options\" -variant \"$xkb_variant\"
