# This file is part of ctkarch-sysconfig.
#
# ctkarch-sysconfig 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 2 of the License, or
# (at your option) any later version.

menu() {
  local items=('chhostname'      "$_hostname"
               'chsyslang'       "$_syslanguage"
               'chconsolekeymap' "$_consolekeymap"
               'chtimezone'      "$_timezone")
  local item="${items[0]}" err
  while
    item="$(dialogmenu --default-item "$item" 2>&1>&3)"
    [[ "$item" != '' ]]
  do
    err="$("$item" 2>&1>&3)" || mydialog --msgbox "${err}" 10 72
  done
  return 0
}

defaults() {
  # One needs a hostname, try to get it from rc.conf or set something if none found
  local hn1 hn2 hn3 hostname i
  # Try to get the hostname from an old rc.conf(.pacsave) and from /etc/hostname
  [ -f "${systemroot}/etc/rc.conf" ] && hn1="$(source "${systemroot}/etc/rc.conf"; echo "$HOSTNAME")"
  [ -f "${systemroot}/etc/rc.conf.pacsave" ] && hn2="$(source "${systemroot}/etc/rc.conf.pacsave"; echo "$HOSTNAME")"
  [ -f "${systemroot}/etc/hostname" ] && hn3="$(<"${systemroot}/etc/hostname")"
  for i in hn1 hn2 hn3;do [ -n "${!i}" ] && hostname="${!i}";done

  # If really no hostname was found, set this
  [ -z "$hostname" ] && hostname=archbox

  sethostname "$hostname" || echo 'sethostname FAILED' >&2;

  # Default settings for the current language, defined in the localization file for this module
  setlocale "$_defaultlocale" || echo 'setlocale FAILED' >&2
  setconsolekeymap "$_defaultkeymap" || echo 'setconsolekeymap FAILED' >&2
  settimezone "$_defaulttimezone" || echo 'settimezone FAILED' >&2
}

# Interactively choose the hostname
chhostname() {
  local hn
  local _title="$_hostname"
  if
    [ -f "${systemroot}/etc/hostname" ] && local rhn="$(<"${systemroot}/etc/hostname")"
    hn="$(mydialog --title "$_hostname" --inputbox '' 6 70 "$rhn" 2>&1>&3)"
  then
    sethostname "$hn" || return 1
    mydialog --msgbox "$_explain_hostname" 10 72
  fi
}

# Set the hostname in /etc/hostname and /etc/hosts
# parms: new_hostname
sethostname() {
  [ -z "$1" ] && { echo "$_emptyinput" >&2; return 1; }
  [ -n "$(echo "$1" |grep '[[:space:]]')" ] && { echo "$_spacesinhostname" >&2; return 1; }

  # get any other existing hostname than localhost
  local oldhn
  [ -f "${systemroot}/etc/hostname" ] && oldhn="$(<"${systemroot}/etc/hostname")"
  [ "$oldhn" = 'localhost' ] && oldhn=''

  # if there's an old hostname, remove it from /etc/hosts
  [ -n "$oldhn" ] && { sed -Ei "/^[[:space:]]*[^#]/s/[[:space:]]+${oldhn}([[:space:]]+|$)/\1/" "${systemroot}/etc/hosts" || return 1; }

  # append new hostname in /etc/hosts
  sed -Ei "s/^([[:space:]]*(127\.0\.0\.1|\:\:1).*)\$/\1 ${1}/" "${systemroot}/etc/hosts" || return 1

  # and set it
  echo "$1" > "${systemroot}/etc/hostname" || return 1

  echo "hostname: $1"
}

chsyslang() {
  [ -d "${systemroot}/usr/share/i18n/locales" ] || { echo "$_localenotfound (/usr/share/i18n/locales/)" >&2; return 1; }
  local i items
  for i in $(ls "${systemroot}/usr/share/i18n/locales" | grep -E '^[a-z]+_[A-Z]+$');do
    items+=("$i" "${i/_/ }")
  done

  local lng _title="$_syslanguage" _hint="$_langletterhint"
  if lng="$(dialogmenu --default-item "${_defaultlocale%.*}" 2>&1>&3)";then
    mydialog --infobox "$_configuringlang" 4 40
    setlocale "${lng}.UTF-8" || return 1
    mydialog --msgbox "$_explain_syslang" 10 72
  fi
}

chconsolekeymap() {
  [ -d "${systemroot}/usr/share/kbd/keymaps" ] || { echo "$_keymapnotfound (/usr/share/kbd/keymaps)" >&2; return 1; }
  local i
  local items
  for i in "${systemroot}/usr/share/kbd/keymaps/i386"/*;do
    [ "$i" != "${systemroot}/usr/share/kbd/keymaps/i386/include" ] && items+=("$i" "${i##*/}")
  done

  local mapfamily _title="$_consolekeymap"
  if mapfamily="$(dialogmenu 2>&1>&3)";then
    if
      unset items; local items
      for i in "${mapfamily}"/*.map.gz;do
        local n="${i%.map.gz}"
        items+=("${n##*/}" "${n##*/}")
      done
      local keymap
      keymap="$(dialogmenu 2>&1>&3)"
    then
      setconsolekeymap "${keymap}" || return 1
      mydialog --msgbox "$_explain_keymap" 10 72
    fi
  fi
}

chtimezone() {
  [ -f "${systemroot}/usr/share/zoneinfo/zone.tab" ] || { echo "$_timezonenotfound (/usr/share/zoneinfo/zone.tab)" >&2; return 1; }
  local i
  local items
  for i in $(grep '^[A-Z]' "${systemroot}/usr/share/zoneinfo/zone.tab" | cut -f 3 | sed -e 's#/.*##g'| sort -u);do
    items+=("$i" "$i")
  done

  local region
  local _title="$_timezone"
  if region="$(dialogmenu 2>&1>&3)";then
    if
      unset items; local items
      for i in $(grep '^[A-Z]' "${systemroot}/usr/share/zoneinfo/zone.tab" | grep "${region}/" | cut -f 3 | sed -e "s#${region}/##g"| sort -u);do
        items+=("$i" "$i")
      done
      local zone
      zone="$(dialogmenu 2>&1>&3)"
    then
      settimezone "${region}/${zone}" || return 1
      mydialog --msgbox "$_explain_timezone" 10 72
    fi
  fi
}

# Edit uncommented variable=value line(s) in file
# parms: variable newvalue file
setvalue() {
  if grep -qE "^[[:space:]]*${1}[[:space:]]*=" "$3" &>/dev/null;then
    sed -Ei "s/^[[:space:]]*${1}[[:space:]]*=.*$/${1}=${2}/" "$3" || return 1
  else
    echo "${1}=${2}" >> "$3" || return 1
  fi
}

# Set locale
# parm: locale
setlocale() {
  # return an error if we don't seem to have it available
  [ -f "${systemroot}/usr/share/i18n/locales/${1%.*}" ] || { echo "$_localenotfound (/usr/share/i18n/locales/${1%.*})" >&2; return 1; }
  grep -qE "^[[:space:]]*#?[[:space:]]*${1}[[:space:]]+" "${systemroot}/etc/locale.gen" || { echo "$_localenotfound (/etc/locale.gen)" >&2; return 1; }
  # make sure everything is commented in locale.gen
  sed -Ei "s/^[[:space:]]*([^#[:space:]])/#\1/" "${systemroot}/etc/locale.gen" || return 1
  # uncomment the new locale in locale.gen
  sed -Ei "s/^[[:space:]]*#[[:space:]]*(${1}[[:space:]]+)/\1/" "${systemroot}/etc/locale.gen" || return 1
  # configure it in locale.conf
  setvalue LANG "$1" "${systemroot}/etc/locale.conf" || return 1
  # generate locale
  chroot_command /usr/bin/locale-gen >&2 || return 1
  echo "locale: $1"
}

# Set console keymap
# parm: console_keymap
setconsolekeymap() {
  [ -n "$(find "${systemroot}/usr/share/kbd/keymaps" -name "${1}.map.gz")" ] || { echo "${1}: $_keymapnotfound" >&2; return 1; }
  setvalue KEYMAP "$1" "${systemroot}/etc/vconsole.conf" || return 1
  echo "console keymap: $1"
}

# Set timezone
# parm: timezone
settimezone() {
  [ -f "${systemroot}/usr/share/zoneinfo/${1}" ] || { echo "/usr/share/zoneinfo/${1}: $_timezonenotfound" >&2; return 1; }
  ln -sf "/usr/share/zoneinfo/${1}" "${systemroot}/etc/localtime" || return 1
  echo "timezone: $1"
}
