#!/usr/bin/env bash
# migrate/cron -- stop the old panel's schedules
#
# Renamed, not deleted: if the operator finds something missing, enabling the
# entry again is one rename away.
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 mig_m_cron)"

targets=()
for f in /etc/cron.d/nhanhvps*; do
    [ -e "$f" ] || continue
    case $f in *.disabled) continue ;; esac
    # our own schedules are created by the panel and always call /usr/bin/nhanhvps
    grep -q 'nhanhvps run backup' "$f" 2>/dev/null && continue
    targets+=("$f")
done

if [ ${#targets[@]} -eq 0 ]; then
    ui_ok "$(t mig_cron_none)"
    exit 0
fi

for f in "${targets[@]}"; do
    printf '  %-42s\n' "$(basename "$f")"
    sed -n '1,6p' "$f" | grep -vE '^\s*$' | sed 's/^/      /'
done
ui_blank
ui_warn "$(t mig_cron_warn "${#targets[@]}")"
ui_confirm "$(t mig_cron_q)" n || { ui_info "$(t pf_cancelled)"; exit 0; }

n=0
for f in "${targets[@]}"; do
    if mv "$f" "$f.disabled"; then n=$((n + 1)); fi
done
nv_trace migrate-cron "disabled $n entry(ies)"
ui_ok "$(t mig_cron_done "$n")"
exit 0
