#!/usr/bin/env bash
# system/reboot-check -- is a reboot pending, and can it be scheduled safely?
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_reboot)"

ui_kv "$(t reboot_uptime)" "$(nv_human_duration "$(nv_uptime_sec)")"
ui_kv "$(t reboot_kernel)" "$(uname -r)"

if [ -f /var/run/reboot-required ]; then
    ui_warn "$(t reboot_required)"
    [ -s /var/run/reboot-required.pkgs ] && sed 's/^/  - /' /var/run/reboot-required.pkgs | head -n 10
else
    ui_ok "$(t reboot_not_required)"
fi
ui_blank

if ui_confirm "$(t reboot_schedule_q)" n; then
    printf '  %s [5]: ' "$(t reboot_minutes)"
    read -r mins || exit 130
    mins=$(nv_trim "$mins"); [ -z "$mins" ] && mins=5
    case $mins in ''|*[!0-9]*) ui_err "$(t ui_invalid_number)"; exit 2 ;; esac
    if nv_is_container; then
        ui_err "$(t reboot_container)"
        exit 1
    fi
    ui_warn "$(t reboot_warn "$mins")"
    ui_confirm_typed "$(t reboot_confirm)" "REBOOT" || { ui_info "$(t pf_cancelled)"; exit 3; }
    if shutdown -r "+$mins" 2>/dev/null; then
        nv_trace reboot "scheduled +${mins}m"
        ui_ok "$(t reboot_scheduled "$mins")"
        ui_info "$(t reboot_cancel_hint)"
    else
        nv_fail 6109 "$(t reboot_failed)"
        exit 1
    fi
fi
exit 0
