#!/bin/sh
#(c) Copyright 2009 Barry Kauler
#2009 Lesser GPL licence v2 (http://www.fsf.org/licensing/licenses/lgpl.html)
#w001 initial creation.
#w004 checkbox for utf8. w019 fixup.
#w470 $1=composeonly option, when call from 3builddistro. 
#w473 disable en_US.utf8 generation, hangs PC if low RAM (64MB system).
#w478 bugfix, dialog_table was incorrect.
#v431 updated LANGUAGEDESCR variable.
#w0910 /usr/share/i18n/charmaps may not be gzipped (ubuntu karmic).
#101120 default to utf8 (see /etc/profile), workaround localedef crash problem in 64MB PC.
#110405 fix different versions of busybox, free has different output format.
#110409 changed locale names .utf8 to .UTF-8.
#110505 support sudo for non-root user.
#111016 param 'composeonly' to generate both /usr/share/i18n/dialog_table_cli and dialog_table_x.

[ "`whoami`" != "root" ] && exec sudo -A ${0} ${@} #110505

LANG=C #Xdialog seems to need this.
export LANG

PARAM1=""
[ $1 ] && PARAM1="$1"

. /etc/DISTRO_SPECS

CURRLANG="`grep '^LANG=' /etc/profile | cut -f 2 -d '='`"

UTF8=''
[ "`echo -n "$CURRLANG" | grep 'utf8'`" != "" ] && UTF8='.utf8'
[ "`echo -n "$CURRLANG" | grep 'UTF\-8'`" != "" ] && UTF8='.UTF-8' #110405

BASELANG="`basename $CURRLANG .utf8`"
BASELANG="`basename $BASELANG .UTF-8`" #110405
CURRENTWM="`cat /etc/windowmanager`"
XSTATUS="cli"
[ -z $DISPLAY ] || XSTATUS="x"
[ $1 ] && XSTATUS="cli"

if [ "$XSTATUS" != "x" ];then
 echo -n -e " \\033[1;35mplease wait...\\033[0;39m" #purple text.
fi

if [ "$PARAM1" != "composeonly" ];then #w470 w473
 #[ ! -d /usr/lib/locale/en_US ] && localedef -f ISO-8859-1 -i en_US --no-archive en_US >/dev/null
 #[ ! -d /usr/lib/locale/en_US.utf8 ] && localedef -f UTF-8 -i en_US --no-archive en_US.utf8 >/dev/null
 #101120 want to default to utf8, but localedef crash problem in 64MB PC...
 if [ "$UTF8" = "" ];then
  [ ! -d /usr/lib/locale/en_US ] && localedef -f ISO-8859-1 -i en_US --no-archive en_US >/dev/null
 else
  #110405 warning: free output varies different versions of busybox (also early version do not accept params)...
  RAMK=`free | tr -s ' ' | grep -o 'Mem:.*' | cut -f 2 -d ' '` #110405
  if [ $RAMK -gt 100000 ];then
   [ -d /usr/lib/locale/en_US.utf8 ] && rm -rf /usr/lib/locale/en_US.utf8 #110409
   [ ! -d /usr/lib/locale/en_US.UTF-8 ] && localedef -f UTF-8 -i en_US --no-archive en_US.UTF-8 >/dev/null #110409
  else
   [ ! -d /usr/lib/locale/en_US ] && localedef -f ISO-8859-1 -i en_US --no-archive en_US >/dev/null
   UTF8=''
  fi
 fi
fi

#v431 fix es:Mexican change to es:Spanish (Spain)...
LANGUAGEDESCR='aa:Afar ab:Abkhazian af:Africaans am:Amharic an:Aragonese ar:Arabic az:Azeri be:Belarusian bn:Bengali bs:Bosnian bg:Bulgarian br:Breton ca:Catalan cs:Czech cy:Welsh da:Danish de:German dv:Divehi dz:Dzongkha el:Greek en:English eo:Esperanto es:Spanish et:Estonian eu:Basque fa:Persian fo:Faeroese fi:Finnish fr:French ga:Irish gd:Scots_Gaelic gl:Galician gv:Manx_Gaelic gu:Gujarati he:Hebrew hi:Hindi hr:Croatian hu:Hungarian hy:Armenian is:Icelandic id:Indonesian iw:Hebrew it:Italian ja:Japanese ka:Georgian kl:Greenlandic kn:Kannada kk:Kazakh km:Khmer kok:Konkani ko:Korean ku:Kurdish kw:Cornish ky:Kyrgyz lg:Luganda lo:Lao lt:Lithuanian lv:Latvian mg:Malagasy ms:Malay ml:Malayalam mt:Maltese mi:Maori mk:Macedonian mn:Mongolian mr:Marathi ne:Nepali nl:Dutch nb:Norgwegian nn:Norwegian_Nynorsk no:Norwegian_Bokm oc:Occitan om:Oromo or:Oriya pa:Pashto pl:Polish pt:Portuguese pa:Punjabi quz:Quechua ro:Romania rs:Serbian ru:Russian rw:Kinyarwanda smn:Sami smj:Sami se:Sami sa:Sanskrit sma:Sami sms:Sami sq:Albanian sr:Srpski sl:Slovenian sw:Swahili sv:Swedish syr:Syriac ta:Tamil th:Thai tl:Tagalog tt:Tatar te:Telugu tr:Turkish uk:Ukrainian ur:Urdu uz:Uzbek vi:Vietnamese wa:Walloon xh:Xhosa yi:Yiddish zh:Chinese zu:Zulu'
REGIONDESCR='AA:ArabicCountries AE:UAE AL:Yugoslavia AR:Argentina AT:Austria AU:Australia BE:Belgium BG:Bularia BH:Bahrain BN:Brunei BO:Bolvia BR:Brazil BZ:Belize CA:Canada CH:Switzerland CL:Chile CN:PeoplesRepublicChina CO:Columbia CR:CostaRica CY:Cyprus CZ:CzechRepublic DE:Germany DK:Denmark DO:DominicanRepublic EC:Ecuador EE:Estonia ES:Spain DO:Dominican DZ:Algeria EC:Ecuador EG:Egypt FI:Finland FR:France GB:GreatBritain GR:Greece GT:Guatemalia HK:HongKong HN:Honduras HR:Croatia HU:Hungary ID:Indonesia IE:Ireland IL:Israel IN:India IQ:Iraq IS:Iceland IT:Italy JM:Jamaica JO:Jordan JP:Japan KR:Korea KW:Kuwait KZ:Kazakhstan LB:Lebanon LI:Liechtenstein LU:Luxembourg LY:Libya MA:Morocco MC:Monaco MK:Macedonia MO:Macau MY:Malaysia MX:Mexico NI:Nicaragua NL:Netherlands NO:Norway NZ:NewZealand OM:Oman PA:Panama PE:Peru PH:Philippines PL:Poland PR:PuertoRico PT:Portugal PY:Paraguay QA:Qatar RO:Romania RU:Russia SA:SaudiArabia SE:Sweden SG:Singapore SK:Slovakia SY:Syria TH:Thailand TN:Tunisia TR:Turkey TW:Taiwan ZA:SouthAfrica TT:Trinidad US:USA PE:Peru SV:ElSalvador MX:Mexico NI:Nicaragua UY:Uruguay VE:Venezuela YE:Yemen YU:Yugoslavia ZA:SouthAfrica'

#need sanity check, as format these files has changed...
SANITYFLAG='pass'
[ -s /usr/share/i18n/dialog_table_cli ] && [ `cat /usr/share/i18n/dialog_table_cli | wc -l` -le 1 ] && SANITYFLAG='fail'
[ -s /usr/share/i18n/dialog_table_x ] && [ `cat /usr/share/i18n/dialog_table_x | wc -l` -le 1 ] && SANITYFLAG='fail'

#if [ ! -f /usr/share/i18n/dialog_table ];then
if [ "$PARAM1" = "composeonly" -o "$SANITYFLAG" = "fail" ];then #111016
 CHOICES_CLI=""; ON=""; OFF=""; XPID=""; CHOICES_X=""
 if [ "$XSTATUS" = "x" ];then
  xmessage -bg orange -fg black -center -buttons "" "Please wait, processing..." &
  XPID=$!
 fi
 for ONELOCALE in `ls -1 /usr/share/i18n/locales | grep -v -E 'i18n|iso|translit|POSIX'`
 do
  STATUS="off"
  [ "$ONELOCALE" = "$BASELANG" ] && STATUS="on"
  LANGUAGE="`echo -n "$ONELOCALE" | cut -f 1 -d '_'`"
  REGION="`echo -n "$ONELOCALE" | cut -f 2 -d '_' | cut -f 1 -d '.' | cut -f 1 -d '@'`"
  lPATTERN="^${LANGUAGE}:"
  LANGUAGE="`echo "$LANGUAGEDESCR" | tr ' ' '\n' | grep "$lPATTERN" | head -n 1 | cut -f 2 -d ':'`"
  rPATTERN="^${REGION}:"
  REGION="`echo "$REGIONDESCR" | tr ' ' '\n' | grep "$rPATTERN" | head -n 1 | cut -f 2 -d ':'`"
  [ "$LANGUAGE" != "" ] && [ "$REGION" != "" ] && LANGUAGE="${LANGUAGE}, "
  DESCR="${LANGUAGE}${REGION}"
  #[ "$DESCR" != "" ] && DESCR="(${DESCR})"
  if [ "$STATUS" = "on" ];then
   #FIRSTLINE_X="$ONELOCALE \"${DESCR}\" ${ON}"
   CHOICES_X="$CHOICES_X
$ONELOCALE \"${DESCR}\" on"
   FIRSTLINE_CLI="$ONELOCALE \"${DESCR}\" "
  else
   CHOICES_X="$CHOICES_X
$ONELOCALE \"${DESCR}\" off"
   CHOICES_CLI="$CHOICES_CLI
$ONELOCALE \"${DESCR}\" "
  fi
 done
 echo "$CHOICES_X" > /usr/share/i18n/dialog_table_x
 CHOICES_CLI="${FIRSTLINE_CLI}
${CHOICES_CLI}"
 echo "$CHOICES_CLI" > /usr/share/i18n/dialog_table_cli
 [ "$XPID" != "" ] && kill $XPID
 [ "$PARAM1" = "composeonly" ] && exit
else
 if [ "$XSTATUS" = "x" ];then
  #tables already exist, but may need to reselect 'on' item...
  onPTN="s%^${BASELANG} \"(.*)\" off$%${BASELANG} \"\1\" on%"
  sed -i -e 's% on$% off%' -r -e "$onPTN" /usr/share/i18n/dialog_table_x
 fi
fi

CHOICES="`cat /usr/share/i18n/dialog_table_${XSTATUS} | tr '\n' ' '`"

CHECKUTF8='off'
[ "$UTF8" != "" ] && CHECKUTF8='on'

if [ "$XSTATUS" = "x" ];then
 echo "#!/bin/sh
Xdialog --left --stdout --wrap --title \"Country setup\" --check \"UTF-8 encoding (apps faster without)\" ${CHECKUTF8} --radiolist \"The locale setting provides money, date and font localization for your country. The current choice is ${BASELANG}. Make a choice to suit your country...\" 0 46 13 $CHOICES >/tmp/chooselocale-choice
exit \$?" > /tmp/xdialog-chooselocale
else
 echo "#!/bin/sh
dialog --aspect 10 --title \"Country setup\" --menu \"The locale setting provides money, date and font localization for your country. The current choice is ${BASELANG}. Make a choice to suit your country...\" 0 0 0 ${CHOICES} 2>/tmp/chooselocale-choice
exit \$?" > /tmp/xdialog-chooselocale
fi
chmod 777 /tmp/xdialog-chooselocale
/tmp/xdialog-chooselocale
[ $? -ne 0 ] && exit

LANGCHOICE="`cat /tmp/chooselocale-choice | head -n 1`"

if [ "$XSTATUS" = "cli" ];then #101120
 #dialog window does not have a checkbox for this, use whatever was in /etc/profile...
 UTF8CHOICE=""
 [ "$UTF8" ] && UTF8CHOICE="checked"
else
 UTF8CHOICE="`cat /tmp/chooselocale-choice | tail -n 1`"
 UTF8=''
fi
if [ "$UTF8CHOICE" = "checked" ];then
 UTF8='.UTF-8' #110409
 #if the user has chosen something like nl_BE@euro, need to chop...
 LANGCHOICE="`echo -n "$LANGCHOICE" | cut -f 1 -d '@'`"
fi


if [ "$LANGCHOICE" != "" -a "${LANGCHOICE}${UTF8}" != "$CURRLANG" ];then

 # creates locale files in /usr/lib/locale...
 #CURRLANG="`grep '^LANG=' /etc/profile | cut -f 2 -d '='`"
 OLDLANG="LANG=$CURRLANG"
 NEWLANG="LANG=${LANGCHOICE}"
 [ "$UTF8" != "" ] && NEWLANG="LANG=${LANGCHOICE}"'.UTF-8' #110409
 if [ "`locale -a | grep "${LANGCHOICE}${UTF8}"`" = "" ];then
  if [ "$UTF8" = "" ];then
   lcPATTERN='^'"${LANGCHOICE}"' '
   CHARMAP="`grep "$lcPATTERN" /usr/share/i18n/SUPPORTED | head -n 1 | cut -f 2 -d ' '`"
   if [ "$CHARMAP" != "" ];then #make sure have it...
    cPATTERN="$CHARMAP"'\.gz'
    #w0910 what if not gzipped...
    [ "`ls -1 /usr/share/i18n/charmaps | grep '.gz$'`" = "" ] && cPATTERN="$CHARMAP"'$'
    [ "`ls -1 /usr/share/i18n/charmaps | grep "$cPATTERN"`" = "" ] && CHARMAP=""
   fi
   if [ "$CHARMAP" != "" ];then
    localedef -f $CHARMAP -i $LANGCHOICE --no-archive ${LANGCHOICE} > /dev/null
    NEWLANG="LANG=${LANGCHOICE}"
   else
    #no match, i think forced to use utf8...
    localedef -f UTF-8 -i $LANGCHOICE --no-archive ${LANGCHOICE}.UTF-8 > /dev/null #110409
    NEWLANG="LANG=${LANGCHOICE}.UTF-8"
	UTF8='.UTF-8'
   fi
  else
   #lcPATTERN='^'"${LANGCHOICE}"'[. ]'
   #CHARMAP="`grep "$lcPATTERN" /usr/share/i18n/SUPPORTED | grep 'UTF\-8' | head -n 1 | cut -f 2 -d ' '`"
   #[ "$CHARMAP" = "" ] && CHARMAP="UTF-8"
   localedef -f UTF-8 -i $LANGCHOICE --no-archive ${LANGCHOICE}.UTF-8 > /dev/null #110409
   NEWLANG="LANG=${LANGCHOICE}.UTF-8" #110409
  fi
 fi

 if [ "$OLDLANG" != "$NEWLANG" ];then
  langPATTERN="s/${OLDLANG}/${NEWLANG}/"
  sed -e "$langPATTERN" /etc/profile > /tmp/profile
  cp -f /tmp/profile /etc/profile
 fi

 [ "$XSTATUS" != "x" ] && exit
 
 Xdialog --left --wrap --title "Country setup" --ok-label "Restart X now" --cancel-label "Finished"  --yesno "Ok, the change has been made and will take effect at next boot. However, if you click the 'Restart X now' button X will exit then restart and the new locale will immediately take effect -- however make sure that all other applications are closed first as restarting X will rudely kill them! Otherwise, just click 'Finished' for the new locale to take effect at next boot.\n\nTechnical details:\nLocale files have been generated in /usr/lib/locale (if not already) and LANG variable set to ${LANGCHOICE}${UTF8} in /etc/profile." 0 100
 
 if [ $? -eq 0 ];then
  rm -rf /tmp/.X0-lock
  sync
  exec restartwm $CURRENTWM
 fi
 
fi

###END###
