#!/usr/bin/env bash
# security/updates -- security updates without babysitting the server
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 sec_m_updates)"

pending=$(apt-get -s upgrade 2>/dev/null | grep -c '^Inst ')
security=$(apt-get -s upgrade 2>/dev/null | grep '^Inst' | grep -ci security)
ui_kv "$(t upd_pending)" "$pending"
ui_kv "$(t upd_security)" "$security"

if [ -f /etc/apt/apt.conf.d/20auto-upgrades ]; then
    auto=$(grep -c 'Unattended-Upgrade "1"' /etc/apt/apt.conf.d/20auto-upgrades 2>/dev/null)
    [ "${auto:-0}" -gt 0 ] && ui_ok "$(t upd_auto_on)" || ui_warn "$(t upd_auto_off)"
else
    ui_warn "$(t upd_auto_missing)"
fi
ui_blank

ui_info "1) $(t upd_apply)"
ui_info "2) $(t upd_enable_auto)"
ui_info "0) $(t menu_back)"
ui_blank
printf '  %s: ' "$(t menu_prompt_short)"
read -r pick || exit 130

case $pick in
    0) exit 0 ;;
    1)
        ui_confirm "$(t upd_apply_q)" n || exit 0
        ui_step "$(t upd_running)"
        pkg_update || true
        if DEBIAN_FRONTEND=noninteractive apt-get -y -q upgrade; then
            nv_trace updates applied
            ui_ok "$(t upd_applied)"
        else
            nv_fail 2103 "$(t upd_failed)"
            exit 1
        fi
        ;;
    2)
        if pkg_install unattended-upgrades; then
            cat >/etc/apt/apt.conf.d/20auto-upgrades <<'EOF'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
EOF
            nv_trace updates auto-enabled
            ui_ok "$(t upd_auto_enabled)"
        else
            nv_fail 2104 "$(t upd_failed)"
            exit 1
        fi
        ;;
    *) ui_err "$(t menu_invalid)"; exit 2 ;;
esac
exit 0
