#!/usr/bin/env bash
# Collector systemd drop-in: KillMode=process (uartd survives stop/restart) and
# User=topbox (logs in ~/EtherGold/logs must be rotatable by log_offload.sh).
#
# Idempotent. Promote / rollback / log_offload all run this.
# Restarts ethergold-collector only when the live MainPID is not topbox
# (KillMode=process is in this same drop-in, applied before that restart).
#
#   bash ~/EtherGold/sync/install_uartd_persist_dropin.sh
#   SKIP_UARTD_PERSIST_DROPIN=1 bash …          # no-op
#   COLLECTOR_RESTART_IF_ROOT=0 bash …          # drop-in + chown only
#
# Needs sudo -n. Never sudo reboot. Never pkill.

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_UARTD_PERSIST_DROPIN:-0}" == "1" ]]; then
  echo "install_uartd_persist_dropin: SKIP_UARTD_PERSIST_DROPIN=1"
  exit 0
fi

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

DROPIN_NAME="uartd-persist.conf"
UNITS=(ethergold-collector.service fixture-collector.service)
LOGS_DIR="${ETHERGOLD_LOGS:-${HOME}/EtherGold/logs}"
RESTART_IF_ROOT="${COLLECTOR_RESTART_IF_ROOT:-1}"

sudo -n true 2>/dev/null || {
  echo "FATAL: sudo -n failed; cannot write systemd drop-in." >&2
  exit 1
}

unit_installed() {
  systemctl cat "$1" &>/dev/null
}

apply_one() {
  local unit="$1"
  local dir="/etc/systemd/system/${unit}.d"
  local path="${dir}/${DROPIN_NAME}"
  sudo -n mkdir -p "${dir}"
  sudo -n tee "${path}" >/dev/null <<EOF
# Applied by install_uartd_persist_dropin.sh (Promote + log_offload).
[Service]
User=topbox
Group=topbox
SupplementaryGroups=dialout gpio
KillMode=process
TimeoutStopSec=15
Type=notify
NotifyAccess=main
WatchdogSec=60
Environment=ETHERGOLD_UARTD_PERSIST=1
Environment=ETHERGOLD_UARTD_ALLOW_SIGKILL=0
EOF
  echo "install_uartd_persist_dropin: ${path}"
}

chown_logs() {
  sudo -n mkdir -p "${LOGS_DIR}"
  sudo -n chown -R topbox:topbox "${LOGS_DIR}"
  echo "install_uartd_persist_dropin: chown topbox:topbox ${LOGS_DIR}"
}

main_pid_user() {
  local unit="$1"
  local pid
  pid="$(systemctl show "${unit}" -p MainPID --value 2>/dev/null || true)"
  if ! [[ "${pid}" =~ ^[1-9][0-9]*$ ]]; then
    echo ""
    return 0
  fi
  ps -o user= -p "${pid}" 2>/dev/null | awk '{print $1}'
}

restart_if_root() {
  local unit="$1"
  if ! systemctl is-active --quiet "${unit}"; then
    echo "install_uartd_persist_dropin: ${unit} inactive — no restart"
    return 0
  fi
  local user
  user="$(main_pid_user "${unit}")"
  if [[ "${user}" == "topbox" ]]; then
    echo "install_uartd_persist_dropin: ${unit} already topbox — no restart"
    return 0
  fi
  if [[ "${RESTART_IF_ROOT}" != "1" ]]; then
    echo "install_uartd_persist_dropin: ${unit} user=${user:-?} — COLLECTOR_RESTART_IF_ROOT=0 skip restart"
    return 0
  fi
  echo "install_uartd_persist_dropin: ${unit} user=${user:-?} — restart (KillMode=process)"
  sudo -n systemctl restart "${unit}"
  sleep 1
  user="$(main_pid_user "${unit}")"
  echo "install_uartd_persist_dropin: ${unit} after restart user=${user:-?}"
}

restart_if_watchdog() {
  local unit="$1"
  local before_type="$2"
  local before_wd="$3"
  if ! systemctl is-active --quiet "${unit}"; then
    echo "install_uartd_persist_dropin: ${unit} inactive — no watchdog restart"
    return 0
  fi
  if [[ "${RESTART_IF_ROOT}" != "1" ]]; then
    echo "install_uartd_persist_dropin: ${unit} Type=${before_type:-?} WatchdogUSec=${before_wd:-?} — skip restart"
    return 0
  fi
  if [[ "${before_type}" == "notify" && "${before_wd}" != "0" && -n "${before_wd}" ]]; then
    echo "install_uartd_persist_dropin: ${unit} already Type=notify watchdog — no restart"
    return 0
  fi
  echo "install_uartd_persist_dropin: ${unit} Type=${before_type:-?} WatchdogUSec=${before_wd:-?} — restart (KillMode=process)"
  sudo -n systemctl restart "${unit}"
  sleep 1
  echo "install_uartd_persist_dropin: ${unit} after watchdog restart Type=$(systemctl show "${unit}" -p Type --value 2>/dev/null || true) WatchdogUSec=$(systemctl show "${unit}" -p WatchdogUSec --value 2>/dev/null || true)"
}

found=0
declare -A _seen_units=()
declare -A _before_type=()
declare -A _before_wd=()
for unit in "${UNITS[@]}"; do
  if unit_installed "${unit}"; then
    frag="$(systemctl show "${unit}" -p FragmentPath --value 2>/dev/null || true)"
    real="$(basename "${frag:-${unit}}")"
    [[ -z "${real}" ]] && real="${unit}"
    [[ -n "${_seen_units[${real}]:-}" ]] && continue
    _seen_units["${real}"]=1
    _before_type["${real}"]="$(systemctl show "${real}" -p Type --value 2>/dev/null || true)"
    _before_wd["${real}"]="$(systemctl show "${real}" -p WatchdogUSec --value 2>/dev/null || true)"
    apply_one "${real}"
    found=1
  fi
done

if [[ "${found}" -eq 0 ]]; then
  echo "install_uartd_persist_dropin: no collector unit installed — skip"
  exit 0
fi

sudo -n systemctl daemon-reload
chown_logs

declare -A _restarted=()
for unit in "${UNITS[@]}"; do
  if unit_installed "${unit}"; then
    frag="$(systemctl show "${unit}" -p FragmentPath --value 2>/dev/null || true)"
    real="$(basename "${frag:-${unit}}")"
    [[ -z "${real}" ]] && real="${unit}"
    [[ -n "${_restarted[${real}]:-}" ]] && continue
    _restarted["${real}"]=1
    km="$(systemctl show "${unit}" -p KillMode --value 2>/dev/null || true)"
    usr="$(systemctl show "${unit}" -p User --value 2>/dev/null || true)"
    typ="$(systemctl show "${unit}" -p Type --value 2>/dev/null || true)"
    wd="$(systemctl show "${unit}" -p WatchdogUSec --value 2>/dev/null || true)"
    echo "install_uartd_persist_dropin: ${unit} User=${usr:-?} KillMode=${km:-?} Type=${typ:-?} WatchdogUSec=${wd:-?}"
    restart_if_root "${unit}"
    restart_if_watchdog "${unit}" "${_before_type[${real}]:-}" "${_before_wd[${real}]:-}"
  fi
done
