#!/bin/sh
# Nomad post-sysupgrade reconciliation — AUTO-STAGED, do not edit.
#
# A firmware "Keep Settings" upgrade restores Nomad's CODE (via
# /lib/upgrade/keep.d/nomad) but NOT its opkg deps nor the /etc/rc.d
# service symlinks. We restore both here on the first boot after a
# flash. This MUST be pure shell: the firmware wipes python3-logging /
# python3-ctypes too, so `nomad` can't even import until opkg restores
# them — the self-heal can't depend on python to fix python.
#
# uci-defaults deletes this script on success; nomad.reconcile.tick
# re-stages it every watchdog cycle so it's present for the next
# upgrade's backup.

# 1) Reinstall the runtime deps the flash removed. Backgrounded: this
#    early in boot the WAN may not be up yet, and procd respawns the
#    services once the packages land. Keep this list in sync with the
#    Depends: line in scripts/build-ipk.sh.
( opkg update && opkg install python3-light python3-logging \
      python3-ctypes openssl-util qrencode ) \
      >/tmp/nomad-reconcile-opkg.log 2>&1 &

# 2) Re-enable the per-hardware service set (recreates the /etc/rc.d
#    symlinks). Pure-shell capability probe so it works before the
#    python deps return: a framebuffer means an LCD (buttond), else the
#    standalone watchdog; gl_modem means cellular (swap). buttond and
#    watchdog are mutually exclusive. These mirror nomad.hardware just
#    enough to get the scheduler breathing; `nomad reconcile` re-applies
#    the authoritative choice in step 3.
/etc/init.d/nomad-api enable 2>/dev/null
if [ -e /dev/fb0 ]; then
    /etc/init.d/nomad-buttond enable 2>/dev/null
else
    /etc/init.d/nomad-watchdog enable 2>/dev/null
fi
command -v gl_modem >/dev/null 2>&1 && /etc/init.d/nomad-swap enable 2>/dev/null

# 3) Once the python deps are back, run the authoritative reconcile
#    (service parity, opt-in boot-MAC restore, audit, hook re-stage).
#    Backgrounded with a bounded wait so we never block boot or spin
#    forever. --skip-deps: step 1 already owns the opkg reinstall.
(
    i=0
    while [ "$i" -lt 60 ]; do
        if [ -x /usr/bin/nomad ] && python3 -c 'import logging, ctypes' 2>/dev/null; then
            /usr/bin/nomad reconcile --reason sysupgrade --skip-deps >/dev/null 2>&1
            break
        fi
        i=$((i + 1))
        sleep 5
    done
) &
exit 0
