#!/usr/bin/env bash
# system/ntp -- keep the clock right, because TLS and cron depend on it
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_ntp)"

ui_kv "$(t sys_time_now)"  "$(date '+%Y-%m-%d %H:%M:%S %Z')"
ui_kv "$(t ntp_synced)"    "$(nv_clock_synced && t state_enabled || t state_disabled)"
if nv_have timedatectl; then
    ui_kv "$(t ntp_service)" "$(timedatectl show -p NTP --value 2>/dev/null)"
fi
ui_blank

if ! nv_have timedatectl; then
    ui_err "$(t ntp_no_timedatectl)"
    exit 1
fi
if ui_confirm "$(t ntp_enable_q)" y; then
    if timedatectl set-ntp true 2>/dev/null; then
        sleep 1
        nv_trace ntp "enabled"
        ui_ok "$(t ntp_enabled)"
        ui_kv "$(t ntp_synced)" "$(nv_clock_synced && t state_enabled || t state_disabled)"
    else
        nv_fail 6110 "$(t ntp_failed)"
        exit 1
    fi
fi
exit 0
