#!/bin/bash
# language-chooser.sh
# Description: Set languages for fast language switching.
#
# Copyright 2019, F123 Consulting, <information@f123.org>
# Copyright 2019, Storm Dragon, <storm_dragon@linux-a11y.org>
#
# This 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, or (at your option) any later
# version.
#
# This software 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 package; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
#--code--
 
# Load functions and reusable code:
source /usr/lib/F123-includes/script_functions.sh
export TEXTDOMAIN=language-chooser
export TEXTDOMAINDIR=/usr/share/locale
source gettext.sh
[[ -r /etc/languages ]] && source /etc/languages

# If no languages are defined, add the system default to the array.
if [[ -z $languages ]]; then
    languages=(${LANG%%.*})
fi

# Supported languages are in an array of their own.
supportedLanguages=(
    ar_EG
    en_US
    es_MX
    pt_BR
)

# Create the menu for each language.
options=""
for i in ${supportedLanguages[@]} ; do
    k="Add"
    for j in ${languages[@]} ; do
        if [[ "$j" == "$i" ]]; then
            k="Remove"
        fi
    done
    # Add each option twice so it is proper format for the menu.
    options+=("$k $i" "$(gettext "$k") $i")
done

ifs="$IFS"
IFS=$'\n'
choice="$(menulist ${options[@]})"
IFS="$ifs"

# Update the languages array.
if [[ "${choice%% *}" == "Add" ]]; then
    languages+=(${choice##* })
else
for i in "${!languages[@]}"; do
   if [[ "${languages[i]}" == "${choice##* }" ]]; then
       unset languages[i]
   fi
done
fi

# Write the updated language options to disk.
echo "languages=(${languages[@]})" | sudo tee /etc/languages &> /dev/null

exit 0
