#!/usr/bin/env bash
# tool/config -- view and change the whitelisted product settings
#
# Only keys with a defined meaning are exposed. Free-form editing of the config
# file would let an operator set a value the code cannot handle.
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 tool_m_config)" "$NV_CONFIG_FILE"

keys=(lang panel_port backup_keep_days)
i=0
for k in "${keys[@]}"; do
    i=$((i + 1))
    ui_kv "$i) $k" "$(nv_conf "$k" -)"
done
ui_kv "0)" "$(t menu_back)"
ui_blank

printf '  %s: ' "$(t menu_prompt_short)"
read -r pick || exit 130
case $pick in ''|*[!0-9]*) ui_err "$(t ui_invalid_number)"; exit 2 ;; esac
[ "$pick" -eq 0 ] && exit 0
[ "$pick" -lt 1 ] || [ "$pick" -gt ${#keys[@]} ] && { ui_err "$(t menu_invalid)"; exit 2; }
key=${keys[$((pick - 1))]}

printf '  %s [%s]: ' "$(t config_new_value "$key")" "$(nv_conf "$key" -)"
read -r val || exit 130
val=$(nv_trim "$val")
[ -z "$val" ] && exit 0

case $key in
    lang)               case $val in vi|en) ;; *) ui_err "$(t config_bad_lang)"; exit 2 ;; esac ;;
    panel_port)         nv_valid_port "$val" || { ui_err "$(t fw_bad_port)"; exit 2; } ;;
    backup_keep_days)   case $val in ''|*[!0-9]*) ui_err "$(t ui_invalid_number)"; exit 2 ;; esac ;;
esac

nv_conf_set_persist "$key" "$val"
nv_trace config "$key=$val"
if [ "$key" = "lang" ]; then nv_i18n_set "$val"; fi
ui_ok "$(t config_saved "$key" "$val")"
exit 0
