#!/bin/bash

#timezone selection stuff

function timezone_screen() {
  need_dependency disk &&
  need_dependency install_start &&
  tz_menu
}

function timezone_auto() {
  debug_log "timezone" 1 "selected UTC as timezone since none was configured"
  ln -sf /usr/share/zoneinfo/UTC $FINALFILES/etc/localtime
}

tz_menu()  {

  local selectedTZ="/usr/share/zoneinfo"

  while [ -d $selectedTZ ] ;do
    if [[ "$selectedTZ" == "/usr/share/zoneinfo" ]] ;then
      local answer
      answer=$( run_dialog --title "Time Zone Selection Menu" \
        --menu "Select a timezone or a directory to look in"  \
        0 0 0 $(tz_show $selectedTZ)                         ) ||
      return 1 # fail out when the dialog is aborted
      selectedTZ="$selectedTZ/$answer"
    else # Don't show ".." if we're at top level
      local answer
      answer=$( run_dialog --title "Time Zone Selection Menu"    \
        --menu "Select timezone or directory (we're in $selectedTZ)" \
        0 0 0 ".." "Up one level" $(tz_show $selectedTZ)         ) ||
      return 1
      if [[ "$answer" == ".." ]] ;then
        selectedTZ=${selectedTZ%/*}
      else
        selectedTZ=$selectedTZ/$answer
      fi
    fi
  done

  if ! [ -f "$selectedTZ" ]; then
    debug_log "timezone" 0 "got invalid time zone $selectedTZ"
    return 2 # This should _never_ happen
  fi
  # if we've reached this point, we probably have a valid time zone
  debug_log "timezone" 1 "selected time zone $selectedTZ"

  # configure the local time zone
  try_run ln -sf "$selectedTZ" "${FINALFILES}/etc/localtime"
  # and /etc/ is writable now too
  try_run ln -sf "$selectedTZ" /etc/localtime
  fill_dependency timezone "$selectedTZ"

  if run_dialog                    \
       --title "GMT or local time" \
       --yes-label "local"         \
       --no-label  "GMT"           \
       --yesno "Should the hardware clock store time in universal time
(UTC/GMT) or in local time? In universal it doesn't have
to be re-set for dailight saving time, but it messes up
broken OS's like MS Windows."      \
        0 0                 ;then
    debug_log "timezone" 1 "selected local time in hwclock"
    try_run sed -i 's/^UTC=.*$/UTC=no/' ${FINALFILES}/etc/sysconfig/hwclock
  else
    debug_log "timezone" 1 "selected GMT in hwclock"
    try_run sed -i 's/^UTC=.*$/UTC=yes/' ${FINALFILES}/etc/sysconfig/hwclock
  fi
}

tz_show()  {
  grep "^$1:" $STATE_DIR/timeZoneList | cut -d: -f2-3 | tr : ' '
}
