#!/bin/sh -e

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

i18n_conf=/etc/sysconfig/i18n
mapping_file="/usr/share/predator/i18n.language"

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

Written by Stanislav Ievlev

Copyright (C) 2004 ALT Linux Team
EOF
	exit
}

list_locales()
{
    for locale_name in $(locale -a|egrep -v 'C|POSIX')
    do
	name=$(LC_ALL=$locale_name locale title)
	charset=$(LC_ALL=$locale_name locale charmap)
	if echo $locale_name | grep -qs '\.'; then
	    locale_name=${locale_name%%\.*}
	    echo "$locale_name.$charset	$name	$charset"
	else
	    echo "$locale_name	$name	$charset"
	fi
    done
}

#TODO: move to predator-common
add_or_subst()
{
    if grep -qs "^$1=" $3 2>/dev/null; then
	subst "s,^$1=.*,$1=$2," $3
    else
	echo "$1=$2" >>$3
    fi
}

set_i18n()
{
    mkdir -p /etc/sysconfig ||:
    if list_locales|grep -qs "^$1"; then
	language=$(cat $mapping_file|egrep "^$1:?")
	supported=${1%%\.*}
	add_or_subst "LANG" "$1" $i18n_conf
	add_or_subst "LANGUAGE" "$language" $i18n_conf
	add_or_subst "SUPPORTED" "$supported" $i18n_conf
    else
	echo "unsupported locale"
	exit 1
    fi
}

print_usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
Usage: $PROG [--list] [--get]
or: $PROG --set <locale> [--supported <list of the locales>] [--mapping file]

utility to manipulate system's i18n state

Valid options are:
  -h, --help	display help screen
  -v, --version	display version information
  -l, --list	get list of the installed locales
  -L, --get-list	get list of the installed locales (only codes)
  -g, --get-lang	get current locale
  -G, --get-supported	get list of supported locales
  -m, --mapping	lang-language mapping
  -s, --set	change system locale
  -c, --config	system i18n config

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


TEMP=`getopt -n $PROG -o l,L,h,v,g,G,s:,c:,m: -l get-list,list,help,version,get-lang,get-supported,set:,config:,mapping: -- "$@"` || print_usage
eval set -- "$TEMP"

while :; do
	case "$1" in
		-h|--help) print_usage 0
			;;
		-v|--version) print_version
			;;
		-l|--list) list_locales; break
			;;
		-L|--get-list) list_locales|cut -f1; break
			;;
		-g|--get-lang)
			cat $i18n_conf 2>/dev/null |grep  '^LANG='|sed 's,^LANG=,,' ||:;
			break
			;;
		-G|--get-supported) echo "not implemented yet"; break;
			;;
		-s|--set) shift; set_i18n $1; break;
			;;
		-c|--config) shift; i18n_conf=$1
			;;
		-m|--mapping) shift; mapping_file=$1
			;;
		--) shift; break
			;;
		*) Fatal "unrecognized option: $1"
			;;
	esac
	shift
done
