#!/bin/bash
function check_dialog()
{
    if ! dialog &> /dev/null
    then 
        echo "ERROR: dialog binary not found."
        exit 1
    fi
}
function check_database()
{
    if ! mysql -uroot -p$mysqlrootpwd asterisk -e "show tables" &> /dev/null
    then
        echo "ERROR: Cannot connect to Datbase."
        exit 1
    fi
}
function logo()
{
  dialog --stdout --sleep 1 --backtitle "$BACKTITLE" \
         --infobox " O @ @\n @ @ O\n @ O O\n   O\nIssabel" \
        7 11
}
check_dialog
source /etc/issabel.conf
if [ -z $mysqlrootpwd ]
then
    echo "ERROR: Cannot load /etc/issabel.conf"
    exit 1
fi
check_database
selLang=$((dialog --backtitle "Issabel" --no-tags \
--radiolist "Select PBX language:" 15 40 10 \
 en "English" on \
 es "Spanish" off \
 pt_BR "Portuguese(BR)" off \
 fr "French" off \
 pr "Persian" off \
 > /dev/tty) 2>&1)
if [ -z $selLang ]
then
    #No language selected
    exit 2
fi

#Set *non standard* GUI languages
case $selLang in
    pt_BR)
        webLang="br"
    ;;
    pr)
        webLang="fa"
    ;;
    *)
        webLang=$selLang
    ;;
esac

(
  sqlite3 /var/www/db/settings.db "update settings set value='$webLang' where key='language'"
  mysql -uroot -p$mysqlrootpwd asterisk -e "REPLACE INTO sipsettings(keyword,data) VALUES('sip_language','$selLang');"
  mysql -uroot -p$mysqlrootpwd asterisk -e "REPLACE INTO iaxsettings(keyword,data) VALUES('iax_language','$selLang');"
  mysql -uroot -p$mysqlrootpwd asterisk -e "REPLACE INTO pjsipsettings(keyword,data) VALUES('sip_language','$selLang');"
  #DAHDI
  DAHDI_CFG="/etc/asterisk/chan_dahdi.conf"
  if grep -q "language=" $DAHDI_CFG
  then
      sed -i "s/^language=.*/language=$selLang/g" $DAHDI_CFG
  else
      sed -i "/^\[channels\]/a language=$selLang" $DAHDI_CFG
  fi
) &> /dev/null
logo
if ! amportal a r &> /dev/null
then
    clear
    echo "ERROR: Cannot apply changes."
    exit 3
else
    clear
fi

