#!/usr/bin/env bash
# migrate/detect -- find anything left behind by the previous panel
#
# Two panels writing to the same server silently is worse than either one alone:
# both back up, both rotate logs, both think they own the vhosts.
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"

ui_header "$(t mig_m_detect)"
found=0
report() {  # report PATH LABEL
    if [ -e "$2" ]; then
        ui_warn "$(t mig_found "$1" "$2")"
        found=$((found + 1))
    else
        ui_ok "$(t mig_absent "$1")"
    fi
}

ui_section "$(t mig_legacy_paths)"
report "source tree"   /opt/nhanhvps
report "menu scripts"  /etc/nhanhvps/menu
report "launcher"      /usr/local/bin/nhanhvps
report "banner"        /etc/nhanhvps/nhanhvps
report "global config" /home/nhanhvps.conf

ui_section "$(t mig_legacy_cron)"
cron_hits=0
for f in /etc/cron.d/nhanhvps*; do
    [ -e "$f" ] || continue
    case $f in *.disabled) continue ;; esac
    ui_warn "$(t mig_cron_active "$(basename "$f")")"
    cron_hits=$((cron_hits + 1))
done
[ "$cron_hits" -eq 0 ] && ui_ok "$(t mig_cron_none)"

ui_section "$(t mig_new_install)"
if command -v nhanhvps >/dev/null 2>&1 && [ -r /usr/lib/nhanhvps/VERSION ]; then
    ui_ok "$(t mig_new_ok "$(cat /usr/lib/nhanhvps/VERSION)")"
else
    ui_info "$(t mig_new_running_from_source)"
fi

ui_blank
if [ "$found" -eq 0 ] && [ "$cron_hits" -eq 0 ]; then
    ui_ok "$(t mig_clean)"
else
    ui_warn "$(t mig_found_total "$found" "$cron_hits")"
    ui_info "$(t mig_next_hint)"
fi
exit 0
