#!/bin/bash
# SynSono root infrastructure, revision 5 (15.29.1): the radio services of the board itself off on a SynSono Box.
#
# Run once by the root updater (as a transient systemd unit) or by the root installer scripts, as root, after revision 4.
# Every step can run again without harm.
#
# Armbian for the Orange Pi Zero 3 brings its own services that switch Wi-Fi and Bluetooth on at start-up
# (aw859a-wifi.service, aw859a-bluetooth.service). Since revision 4 their drivers can no longer load, so they failed at
# every start and made the system services of the Box show "Failed". On a SynSono Box they are masked and their failed
# state is cleared, and the board's own request to load its Bluetooth driver (/etc/modules) becomes a comment.
# Revision 4 itself (drivers, guard) stays as it is.
# On any other device (Homebridge with the SynSono updater) nothing changes.
#
# SYNSONO_INFRA_ROOT puts every file under another root directory, for the tests.
set -euo pipefail
ROOT="${SYNSONO_INFRA_ROOT:-}"
REVISION=5
log() { printf '[apply-%s] %s\n' "$REVISION" "$*"; }
fail() { log "FAILED: $*" >&2; exit 1; }
[[ -n "$ROOT" || ${EUID} -eq 0 ]] || fail "run as root"

if [[ ! -s "$ROOT/etc/synsono/appliance.json" ]]; then
  log "not a SynSono Box: nothing to change"
  exit 0
fi
log "SynSono Box"

# The radio services of board images (Armbian and its vendor images); a unit that is not there is skipped.
RADIO_UNITS=(aw859a-wifi.service aw859a-bluetooth.service hciuart.service bluetooth.service wpa_supplicant.service)
for unit in "${RADIO_UNITS[@]}"; do
  systemctl stop "$unit" >/dev/null 2>&1 || true
  systemctl mask "$unit" >/dev/null 2>&1 || log "could not mask $unit (not installed)"
  systemctl reset-failed "$unit" >/dev/null 2>&1 || true
done
# The board image also asks for its Bluetooth driver at every start (/etc/modules: sprdbt_tty). Since revision 4 it
# cannot load; the line is turned into a comment, so nothing tries.
RADIO_MODULES='^(sprdwl_ng|sprdbt_tty|uwe5622_bsp_sdio|cfg80211|mac80211|bluetooth|hci_uart|btqca|btrtl|btbcm|btintel|bnep|rfcomm|brcmfmac|brcmutil|aic8800_fdrv|aic8800_bsp)[[:space:]]*$'
for file in "$ROOT/etc/modules" "$ROOT"/etc/modules-load.d/*.conf; do
  [[ -f "$file" ]] || continue
  if grep -Eq "$RADIO_MODULES" "$file"; then
    sed -i -E "s/$RADIO_MODULES/# \\1  (SynSono Box: Wi-Fi and Bluetooth stay off)/" "$file"
    log "radio modules no longer loaded from ${file#"$ROOT"}"
  fi
done
systemctl daemon-reload
log "the radio services of the board are masked"
log "done"
