#!/bin/bash

### Include ymclibnettools
. /usr/lib/lib-fliwi/ymc-networktools.bash

function ymc_reconfigure_exec
{
  LC_ALL=C DEBIAN_PRIORITY=critical dpkg-reconfigure $@ 2>/dev/null
}

locale=$(ymc_get_hostname_from_dns_txt locale basics)
additional_locales=$(ymc_get_hostname_from_dns_txt locales basics)
keymap=$(ymc_get_hostname_from_dns_txt keymap basics)
timezone=$(ymc_get_hostname_from_dns_txt timezone basics)

### Update the timezone
if [ "$timezone" != '' ]; then
  echo "$timezone" > /etc/timezone
  ymc_reconfigure_exec tzdata
  if [ $? -ne 0 ]; then
    if [ -f "/usr/share/zoneinfo/$timezone" ]; then
      cp -f /usr/share/zoneinfo/$timezone /etc/localtime
    fi
  fi
else
  echo "WARNING: Failed to setup timezone..."
fi

### Update the locales
if [ "$locale" != '' ] && [ "$additional_locales" != '' ]; then
  echo "# Dynamic /etc/locale.gen(5) file generated by $(basename $0)" > /etc/locale.gen
  echo "#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN" >> /etc/locale.gen

  cat /usr/share/i18n/SUPPORTED | sort | while read line
  do
    minimal_line=$(echo $line |cut -d ' ' -f 1 )
    if [ $(ymc_contains "$minimal_line" $additional_locales) -eq 0 ]; then
      echo "# $line" >> /etc/locale.gen
    else
      echo "$line" >> /etc/locale.gen
    fi
  done
  echo "LANG=$locale" > /etc/default/locale
  ymc_reconfigure_exec locales
  if [ $? -ne 0 ]; then
    locale-gen
    if [ -e "/etc/default/locale" ]; then
      /usr/sbin/update-locale --no-checks LANG
    fi
    /usr/sbin/update-locale "LANG=$locale"
  fi
else
  echo "WARNING: Failed to setup locales..."
fi

if [ "$keymap" != '' ]; then
  LC_ALL=C /usr/sbin/install-keymap "$keymap"
else
  echo "WARNING: Failed to setup keymap..."
fi

exit 0
