#!/bin/bash
#
#Copyright 2012 - 2017 CurlyMo, mk01 & mkreisl <development@xbian.org>
#
#This file is part of XBian - XBMC on the Raspberry Pi.
#
#XBian 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.
#
#XBian 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 XBian. If not, see <http://www.gnu.org/licenses/>
#

check_locale()
{
    locale > /tmp/xbian-config.lang 2>/dev/null
    . /tmp/xbian-config.lang 2>/dev/null

    if [ -n "$LC_ALL" ]; then
        lsetting=$LC_ALL
    elif [ -n "$LC_MESSAGES" ]; then
        lsetting=$LC_MESSAGES
    elif [ -n "$LANGUAGE" ]; then
        lsetting="$LANGUAGE"
    elif [ -n "$LANG" ]; then
        lsetting=$LANG
    fi

    [ -z "$lsetting" ] && return 1
    ldir="${lsetting##*=}"
    ldir="${ldir}_."
    ldir="${ldir%%_*.*}"
    [ ! -e "/usr/share/locale/$ldir/LC_MESSAGES/xbian.mo" ] && return 1

    echo -e $(env -i LANG=$lsetting locale) > /run/xbian-config.$$
    return 0

}

if [ ! -e /run/xbian-config.$$ ]; then
    check_locale || echo -e $(env -i LANG=en_US.UTF-8 locale) > /run/xbian-config.$$
    XB_LOCALE=$(cat /run/xbian-config.$$)
    EN_LOCALE=$(env -i LANG="en_US.UTF-8" locale)
fi

function _() {
    msgid="xbian-config.$1"
    translation=$(eval $XB_LOCALE gettext xbian $msgid)
    if [ "$translation" = "$msgid" ]; then
        # Untranslated string
        translation=$(eval $EN_LOCALE gettext xbian $msgid)
    fi

    echo $translation | tr '^' ' '
}
