#!/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)
#   2) systemd oneshot at sysinit (pinctrl)
#   3) run pinctrl now (this boot; no reboot)
#
# Safe on every Pi: older POG-COM-PI-HAT boards do not connect those pads.
# Required on Rev E+: never leave the Pi pin high-Z (TXS PU → DE on).
#
#   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"
UNIT_NAME="ethergold-hs-out-idle.service"
UNIT_PATH="/etc/systemd/system/${UNIT_NAME}"
MARK_B="# BEGIN DYZINETEK_HS_OUT_IDLE"
MARK_E="# END DYZINETEK_HS_OUT_IDLE"

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

_config_txt() {
  if [[ -f /boot/firmware/config.txt ]]; then
    echo /boot/firmware/config.txt
  elif [[ -f /boot/config.txt ]]; then
    echo /boot/config.txt
  else
    echo ""
  fi
}

_uninstall_config() {
  local cfg
  cfg="$(_config_txt)"
  [[ -n "${cfg}" ]] || return 0
  sudo -n python3 - "${cfg}" "${MARK_B}" "${MARK_E}" <<'PY'
import sys
from pathlib import Path
path, begin, end = Path(sys.argv[1]), sys.argv[2], sys.argv[3]
text = path.read_text(encoding="utf-8", errors="replace")
if begin not in text:
    raise SystemExit(0)
pre, rest = text.split(begin, 1)
if end in rest:
    rest = rest.split(end, 1)[1]
    if rest.startswith("\n"):
        rest = rest[1:]
else:
    rest = ""
path.write_text(pre.rstrip() + ("\n" if pre.strip() else "") + rest.lstrip("\n"), encoding="utf-8")
PY
}

if [[ "${1:-}" == "--uninstall" ]]; then
  sudo -n systemctl disable --now "${UNIT_NAME}" 2>/dev/null || true
  sudo -n rm -f "${UNIT_PATH}"
  sudo -n systemctl daemon-reload
  _uninstall_config
  echo "Removed ${UNIT_NAME} (pins left as last driven — not returned to high-Z)"
  exit 0
fi

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
Before=sysinit.target graphical.target ethergold-http.service

[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

cfg="$(_config_txt)"
if [[ -n "${cfg}" ]]; then
  sudo -n python3 - "${cfg}" "${MARK_B}" "${MARK_E}" <<'PY'
import sys
from pathlib import Path
path = Path(sys.argv[1])
begin, end = sys.argv[2], sys.argv[3]
block = (
    f"{begin}\n"
    "# Idle-drive OIS_OUT (BCM10) and M-S_OUT (BCM11) from firmware (before Linux).\n"
    "# Safe on older POG-COM-PI-HAT (pads unconnected). Required on Rev E+ (never high-Z).\n"
    "gpio=10=op,dl\n"
    "gpio=11=op,dl\n"
    f"{end}\n"
)
text = path.read_text(encoding="utf-8", errors="replace")
if begin in text:
    pre, rest = text.split(begin, 1)
    if end in rest:
        rest = rest.split(end, 1)[1]
        if rest.startswith("\n"):
            rest = rest[1:]
    else:
        rest = ""
    text = pre.rstrip() + "\n\n" + block + rest.lstrip("\n")
else:
    if text and not text.endswith("\n"):
        text += "\n"
    text += "\n" + block
path.write_text(text, encoding="utf-8")
print(f"install_hs_out_idle: {path}")
PY
else
  echo "WARN: no /boot/firmware/config.txt or /boot/config.txt — systemd + pinctrl only" >&2
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)"
systemctl is-enabled "${UNIT_NAME}" --quiet && echo "unit enabled" || true
