#!/bin/bash
#
# air-n100-cleanup
#
# Remove stale Raspberry Pi-only helpers/units from Intel N100 / x86_64
# package installs. This is intentionally idempotent: installer repair runs it
# directly, OTA ships it through image_tree, and the companion timer runs it
# shortly after older OTA helpers install it for the first time.

set -u

log() { echo "[air-n100-cleanup] $*" >&2; }

device_arch() {
    if [ -s /etc/air/arch ]; then
        tr -d '[:space:]' </etc/air/arch
    else
        uname -m
    fi
}

case "$(device_arch)" in
    x86_64|amd64) ;;
    *)
        log "skipping: device architecture is $(device_arch)"
        exit 0
        ;;
esac

STALE_UNITS=(
    air-camera-probe.service
    air-resize-rootfs.service
    air-ensure-boot-rw.service
    air-set-hostname.service
    air-mdns-alias.service
    air-wifi-regulatory.service
)

STALE_HELPERS=(
    air-camera-probe
    air-set-camera-overlay
    air-set-hostname
    air-veye-camera-driver
    air-resize-rootfs
    air-ensure-boot-rw
    air-publish-mdns-alias
    air-wifi-regulatory
)

changed=0

for unit in "${STALE_UNITS[@]}"; do
    if [ -e "/etc/systemd/system/${unit}" ] \
            || [ -L "/etc/systemd/system/default.target.wants/${unit}" ] \
            || [ -L "/etc/systemd/system/multi-user.target.wants/${unit}" ] \
            || [ -L "/etc/systemd/system/timers.target.wants/${unit}" ] \
            || systemctl is-enabled "$unit" >/dev/null 2>&1 \
            || systemctl is-active "$unit" >/dev/null 2>&1; then
        log "removing stale Pi-only unit: ${unit}"
        systemctl disable --now "$unit" >/dev/null 2>&1 || true
        rm -f "/etc/systemd/system/${unit}"
        rm -f "/etc/systemd/system/default.target.wants/${unit}"
        rm -f "/etc/systemd/system/multi-user.target.wants/${unit}"
        rm -f "/etc/systemd/system/timers.target.wants/${unit}"
        changed=1
    fi
done

for helper in "${STALE_HELPERS[@]}"; do
    if [ -e "/usr/local/sbin/${helper}" ]; then
        log "removing stale Pi-only helper: ${helper}"
        rm -f "/usr/local/sbin/${helper}"
        changed=1
    fi
done

if [ "$changed" = 1 ]; then
    systemctl daemon-reload >/dev/null 2>&1 || true
fi

exit 0
