#!/usr/bin/env bash
# Idle-drive Pi HS OUTs (BCM10 OIS / BCM11 M-S) as early as possible:
#   1) firmware config.txt gpio= (before Linux) — via boot_config_guard.py
#   2) systemd oneshot at sysinit (pinctrl)
#   3) independent boot-config-guard (restores golden config.txt if KMS wiped)
#   4) run pinctrl now (this boot; no reboot)
#
# OS/desktop health outranks HS-idle. boot_config_guard refuses writes that
# would drop dtoverlay=vc4-kms-v3d / arm_64bit=1, keeps a golden copy on
# /var/lib/ethergold/, and repairs at boot.
#
#   bash ~/EtherGold/sync/install_hs_out_idle.sh
#   bash ~/EtherGold/sync/install_hs_out_idle.sh --uninstall
#
# Needs sudo -n. Never sudo reboot. Never inject=1.

if grep -q $'\r' "${BASH_SOURCE[0]}" 2>/dev/null; then
  sed -i 's/\r$//' "${BASH_SOURCE[0]}"
  exec bash "${BASH_SOURCE[0]}" "$@"
fi

set -euo pipefail

if [[ "${SKIP_HS_OUT_IDLE:-0}" == "1" ]]; then
  echo "install_hs_out_idle: SKIP_HS_OUT_IDLE=1"
  exit 0
fi

if [[ "$(id -un)" == root ]]; then
  echo "FATAL: run as topbox (script uses sudo -n)." >&2
  exit 1
fi

SYNC_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IDLE_SH="${SYNC_ROOT}/hs_out_idle_low.sh"
GUARD_PY="${SYNC_ROOT}/boot_config_guard.py"
UNIT_NAME="ethergold-hs-out-idle.service"
UNIT_PATH="/etc/systemd/system/${UNIT_NAME}"
GUARD_UNIT_NAME="ethergold-boot-config-guard.service"
GUARD_UNIT_PATH="/etc/systemd/system/${GUARD_UNIT_NAME}"
# Install guard helper where root units can always find it (not only Dropbox tree).
GUARD_INSTALL_PY="/usr/local/lib/ethergold/boot_config_guard.py"

sudo -n true 2>/dev/null || {
  echo "FATAL: sudo -n failed; cannot install HS OUT idle / boot config guard." >&2
  exit 1
}

if [[ ! -f "${GUARD_PY}" ]]; then
  echo "FATAL: missing ${GUARD_PY}" >&2
  exit 1
fi

_install_guard_binary() {
  sudo -n mkdir -p /usr/local/lib/ethergold /var/lib/ethergold
  sudo -n cp -f "${GUARD_PY}" "${GUARD_INSTALL_PY}"
  sudo -n chmod 755 "${GUARD_INSTALL_PY}"
}

_install_guard_unit() {
  _install_guard_binary
  sudo -n tee "${GUARD_UNIT_PATH}" >/dev/null <<EOF
[Unit]
Description=EtherGold — repair /boot/firmware/config.txt from golden if KMS wiped
Documentation=file:${GUARD_INSTALL_PY}
DefaultDependencies=no
After=local-fs.target
Before=sysinit.target graphical.target display-manager.service lightdm.service ${UNIT_NAME}

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/python3 ${GUARD_INSTALL_PY} repair
# Exit 1 = unhealthy with no golden (journal failed). Boot still continues;
# operator must fix golden before next HS-idle rewrite.

[Install]
WantedBy=sysinit.target
EOF
  sudo -n systemctl daemon-reload
  sudo -n systemctl enable "${GUARD_UNIT_NAME}"
  # Run now so golden exists before the next soft/hard cycle.
  sudo -n systemctl start "${GUARD_UNIT_NAME}" || true
  echo "Enabled ${GUARD_UNIT_NAME}"
}

if [[ "${1:-}" == "--uninstall" ]]; then
  sudo -n systemctl disable --now "${UNIT_NAME}" 2>/dev/null || true
  sudo -n rm -f "${UNIT_PATH}"
  # Keep boot-config-guard enabled — desktop safety must remain.
  _install_guard_unit
  sudo -n python3 "${GUARD_INSTALL_PY}" remove-hs-idle || {
    echo "FATAL: remove-hs-idle refused or failed (config left healthy if golden restore ran)." >&2
    exit 1
  }
  sudo -n systemctl daemon-reload
  echo "Removed ${UNIT_NAME}; ${GUARD_UNIT_NAME} kept for desktop safety"
  exit 0
fi

# --- install path ---
_install_guard_unit

sudo -n tee "${UNIT_PATH}" >/dev/null <<EOF
[Unit]
Description=Pi HS OUT idle low (BCM10 OIS_OUT / BCM11 M-S_OUT)
Documentation=file:${IDLE_SH}
DefaultDependencies=no
After=local-fs.target ${GUARD_UNIT_NAME}
Before=sysinit.target graphical.target ethergold-http.service
RequiresMountsFor=/boot/firmware

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/pinctrl set 10 op dl
ExecStart=/usr/bin/pinctrl set 11 op dl

[Install]
WantedBy=sysinit.target
EOF

sudo -n systemctl daemon-reload
sudo -n systemctl enable "${UNIT_NAME}"
sudo -n systemctl start "${UNIT_NAME}" || true

# Snapshot golden from healthy live config, then apply HS block (or refuse).
sudo -n python3 "${GUARD_INSTALL_PY}" ensure-golden || true
if ! sudo -n python3 "${GUARD_INSTALL_PY}" apply-hs-idle; then
  echo "FATAL: apply-hs-idle refused — /boot/firmware/config.txt left healthy (or restored)." >&2
  echo "       Fix OS config / golden before retrying HS idle gpio stanza." >&2
  exit 1
fi

if [[ -f "${IDLE_SH}" ]]; then
  sed -i 's/\r$//' "${IDLE_SH}" 2>/dev/null || true
  chmod +x "${IDLE_SH}" || true
  bash "${IDLE_SH}" || echo "WARN: hs_out_idle_low.sh failed (need sudo -n pinctrl)" >&2
fi

echo "Enabled ${UNIT_NAME} (firmware gpio= takes effect on next hard power cycle)"
echo "Desktop guard: ${GUARD_UNIT_NAME} + golden at /var/lib/ethergold/boot-config-golden.txt"
systemctl is-enabled "${UNIT_NAME}" --quiet && echo "hs-out-idle unit enabled" || true
systemctl is-enabled "${GUARD_UNIT_NAME}" --quiet && echo "boot-config-guard unit enabled" || true
