#!/usr/bin/env bash
# system/timezone -- set the system time zone
#
# A wrong time zone shifts cron schedules and can make TLS validation fail, so
# the change is guarded and confirmed explicitly.
set -o pipefail
SELF=$(readlink -f "${BASH_SOURCE[0]}")
NV_BASE=$(cd "$(dirname "$SELF")/../../.." && pwd)
export NV_BASE
# shellcheck source=/dev/null
. "$NV_BASE/lib/core/bootstrap.sh"

nv_require_root || exit 1
ui_header "$(t sys_m_timezone)"

cur=$(timedatectl show -p Timezone --value 2>/dev/null || cat /etc/timezone 2>/dev/null || echo '?')
ui_kv "$(t sys_tz_current)" "$cur"
ui_kv "$(t sys_time_now)"   "$(date '+%Y-%m-%d %H:%M:%S %Z')"
ui_blank
ui_info "1) Asia/Ho_Chi_Minh"
ui_info "2) UTC"
ui_info "3) $(t sys_tz_other)"
ui_info "0) $(t menu_back)"
ui_blank

printf '  %s: ' "$(t menu_prompt_short)"
read -r pick || exit 130
case $pick in
    0) exit 0 ;;
    1) tz='Asia/Ho_Chi_Minh' ;;
    2) tz='UTC' ;;
    3)
        printf '  %s: ' "$(t sys_tz_prompt)"
        read -r tz || exit 130
        tz=$(nv_trim "$tz")
        ;;
    *) ui_err "$(t menu_invalid)"; exit 2 ;;
esac

if [ ! -e "/usr/share/zoneinfo/$tz" ]; then
    ui_err "$(t sys_tz_invalid "$tz")"
    exit 2
fi
[ "$tz" = "$cur" ] && { ui_info "$(t sys_tz_same)"; exit 0; }

ui_warn "$(t sys_tz_effect)"
ui_confirm "$(t sys_tz_confirm "$tz")" n || { ui_info "$(t pf_cancelled)"; exit 0; }

if nv_have timedatectl; then
    timedatectl set-timezone "$tz" || { nv_fail 6106 "$(t sys_tz_failed)"; exit 1; }
else
    ln -sfn "/usr/share/zoneinfo/$tz" /etc/localtime || { nv_fail 6106 "$(t sys_tz_failed)"; exit 1; }
    printf '%s\n' "$tz" >/etc/timezone
fi
nv_trace timezone "$cur -> $tz"

ui_ok "$(t sys_tz_done "$tz")"
ui_kv "$(t sys_time_now)" "$(date '+%Y-%m-%d %H:%M:%S %Z')"
exit 0
