#!/bin/sh -e
#
#    locale-resolver-config - Configure i18n-locale-resolver database
#    Copyright (C) 2011  Pali Rohár <pali.rohar@gmail.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

DIR="/usr/share/i18n-locale-resolver"
IM_FILE="$DIR/im.data"
LRA_FILE="$DIR/lra_language.data"

if ( test "$1" != "add" && test "$1" != "del" ) || test -z "$2"; then
	echo "Usage: $0: add|del lang"
	echo
	echo "Welcome screen on Maemo 5 (osso_startup_wizzard) using binary"
	echo "database files to show select menu with supported languages."
	echo "This script configure languages visible on welcome screen."
	echo
	echo "This Script add or delete language string from these"
	echo "i18n-locale-resolver database files:"
	echo "$IM_FILE"
	echo "$LRA_FILE"
	echo
	echo "Author: Pali Rohár <pali.rohar@gmail.com>"
	echo "License: GPL v3"
	exit
fi

if test "$(id -u)" != "0"; then
	echo "You must be root"
	exit
fi

IM_DATA="$(dd if=$IM_FILE bs=1 skip=37 2>/dev/null | tr '\000' '\001' | sed $(echo -n -e 's/\117\001\005/\\n/g'))"
LRA_DATA="$(dd if=$LRA_FILE bs=1 skip=47 2>/dev/null | tr '\000' '\001' | sed $(echo -n -e 's/\117\001\005/\\n/g'))"

if test "$1" = "add"; then
	IM_DATA="$IM_DATA
$2"
	LRA_DATA="$LRA_DATA
$2"
elif test "$1" = "del"; then
	IM_DATA=$(echo "$IM_DATA" | grep -v "$2")
	LRA_DATA=$(echo "$LRA_DATA" | grep -v "$2")
fi

dd if="$IM_FILE" of="$IM_FILE.new" bs=1 count=37 2>/dev/null
dd if="$LRA_FILE" of="$LRA_FILE.new" bs=1 count=47 2>/dev/null

echo "$IM_DATA" | sort | uniq | tr '\n' '\001' | sed 's/.$//' | sed $(echo -n -e 's/\001/\117\001\005/g') | tr '\001' '\000' >> "$IM_FILE.new"
echo "$LRA_DATA" | sort | uniq | tr '\n' '\001' | sed 's/.$//' | sed $(echo -n -e 's/\001/\117\001\005/g') | tr '\001' '\000' >> "$LRA_FILE.new"

mv "$IM_FILE.new" "$IM_FILE"
mv "$LRA_FILE.new" "$LRA_FILE"
