#!/usr/bin/env bash
# tool/update -- update the panel itself through the package manager
#
# Only works when installed as a package: updating a source-tree checkout
# behind the operator's back would destroy their local changes.
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_update)"

installed=$(pkg_query nhanhvps 2>/dev/null || true)
running=$(cat "$NV_BASE/VERSION" 2>/dev/null || echo '?')
ui_kv "$(t upd_running_version)"   "$running"
ui_kv "$(t upd_installed_version)" "${installed:-$(t upd_not_packaged)}"

if [ -z "$installed" ]; then
    ui_blank
    ui_info "$(t upd_source_tree)"
    ui_info "$(t upd_source_hint)"
    exit 0
fi

pkg_update >/dev/null 2>&1 || true
candidate=$(apt-cache policy nhanhvps 2>/dev/null | sed -n 's/^ *Candidate: //p' | head -n 1)
ui_kv "$(t upd_candidate)" "${candidate:--}"

if [ -z "$candidate" ] || [ "$candidate" = "(none)" ]; then
    ui_blank
    ui_warn "$(t upd_no_repo)"
    ui_info "$(t upd_repo_hint)"
    exit 0
fi

if [ "$candidate" = "$installed" ]; then
    ui_blank
    ui_ok "$(t upd_latest)"
    exit 0
fi

ui_blank
ui_info "$(t upd_available "$installed" "$candidate")"
ui_confirm "$(t upd_upgrade_q)" y || exit 0

ui_step "$(t upd_upgrading)"
if DEBIAN_FRONTEND=noninteractive apt-get install -y --only-upgrade nhanhvps; then
    nv_trace panel-update "$installed -> $candidate"
    ui_ok "$(t upd_upgraded "$candidate")"
    ui_info "$(t upd_reopen_hint)"
else
    nv_fail 2105 "$(t upd_upgrade_failed)"
    exit 1
fi
exit 0
