#!/usr/bin/env bash
# Install / sync ethergold-pogcc-com.service (Heltec USB CDC + P3 GAMESTATS).
#
# Idempotent. Default mode=auto:
#   - Always refresh the unit file from tip + daemon-reload
#   - If ~/DyzineFrame/config.ini has pogcc_com_owner=ethergold → enable --now
#   - Otherwise stop+disable (safe for seats still on DF USBCDC)
#
# Usage:
#   bash install_pogcc_com_service.sh              # auto (recommended from update.sh)
#   bash install_pogcc_com_service.sh --enable-now # cutover (after DF owner=ethergold + DF restart)
#   bash install_pogcc_com_service.sh --stop       # force stop+disable
#   bash install_pogcc_com_service.sh --unit-only  # install unit; leave enable/active alone
#   SKIP_POGCC_COM=1 …                            # no-op exit 0
#
# Env:
#   ETHERGOLD_ROOT   default ~/EtherGold
#   DYZINEFRAME_ROOT default ~/DyzineFrame
#   POGCC_COM_MODE   auto|enable-now|stop|unit-only (CLI flags override)

set -euo pipefail

if [[ "${SKIP_POGCC_COM:-0}" == "1" ]]; then
  echo "SKIP_POGCC_COM=1 — leave ethergold-pogcc-com unchanged"
  exit 0
fi

EG_ROOT="${ETHERGOLD_ROOT:-$HOME/EtherGold}"
DEV="${EG_ROOT}/dev"
DF_ROOT="${DYZINEFRAME_ROOT:-$HOME/DyzineFrame}"
DF_CFG="${DF_ROOT}/config.ini"
UNIT_SRC="${DEV}/ethergold-pogcc-com.service"
UNIT_DST="/etc/systemd/system/ethergold-pogcc-com.service"
UNIT_NAME="ethergold-pogcc-com.service"

MODE="${POGCC_COM_MODE:-auto}"
for arg in "$@"; do
  case "${arg}" in
    --enable-now|--enable) MODE=enable-now ;;
    --stop|--disable) MODE=stop ;;
    --unit-only) MODE=unit-only ;;
    --auto) MODE=auto ;;
    -h|--help)
      sed -n '2,20p' "$0"
      exit 0
      ;;
    *)
      echo "Unknown arg: ${arg}" >&2
      exit 2
      ;;
  esac
done

if [[ ! -f "${UNIT_SRC}" ]]; then
  echo "Missing ${UNIT_SRC}" >&2
  exit 1
fi
if [[ ! -f "${DEV}/pogcc_com_service.py" ]]; then
  echo "Missing ${DEV}/pogcc_com_service.py" >&2
  exit 1
fi

_read_df_owner() {
  local owner="dyzineframe"
  if [[ -f "${DF_CFG}" ]]; then
    owner="$(
      grep -iE '^[[:space:]]*pogcc_com_owner[[:space:]]*=' "${DF_CFG}" 2>/dev/null \
        | head -n1 \
        | sed -E 's/^[^=]*=[[:space:]]*//; s/[[:space:]]*(#.*)?$//' \
        | tr '[:upper:]' '[:lower:]' \
        | tr -d '\r'
    )"
  fi
  case "${owner}" in
    ethergold) echo ethergold ;;
    *) echo dyzineframe ;;
  esac
}

echo "Installing ${UNIT_NAME} from ${UNIT_SRC} (mode=${MODE})"
TMP="$(mktemp)"
sed "s|/home/topbox/EtherGold|${EG_ROOT}|g" "${UNIT_SRC}" > "${TMP}"
sudo cp -f "${TMP}" "${UNIT_DST}"
rm -f "${TMP}"
sudo systemctl daemon-reload

OWNER="$(_read_df_owner)"
echo "  DF pogcc_com_owner=${OWNER} (${DF_CFG})"

case "${MODE}" in
  unit-only)
    echo "  unit installed; enable/active left unchanged"
    ;;
  enable-now)
    sudo systemctl enable "${UNIT_NAME}"
    sudo systemctl restart "${UNIT_NAME}"
    systemctl --no-pager --full status "${UNIT_NAME}" || true
    echo "Status: /run/ethergold/pogcc-com.status"
    echo "Ensure DF was restarted with pogcc_com_owner=ethergold first (two CDC owners fight)."
    ;;
  stop)
    sudo systemctl stop "${UNIT_NAME}" 2>/dev/null || true
    sudo systemctl disable "${UNIT_NAME}" 2>/dev/null || true
    echo "  stopped+disabled ${UNIT_NAME}"
    ;;
  auto)
    if [[ "${OWNER}" == "ethergold" ]]; then
      sudo systemctl enable "${UNIT_NAME}"
      sudo systemctl restart "${UNIT_NAME}"
      systemctl --no-pager --full status "${UNIT_NAME}" || true
      echo "Status: /run/ethergold/pogcc-com.status"
    else
      # Keep tip unit on disk; do not steal Heltec from DF USBCDC.
      sudo systemctl stop "${UNIT_NAME}" 2>/dev/null || true
      sudo systemctl disable "${UNIT_NAME}" 2>/dev/null || true
      echo "  owner=dyzineframe — unit synced, service stopped+disabled (safe default)"
      echo "  Cutover: set pogcc_com_owner=ethergold, restart DF, then:"
      echo "    bash ${DEV}/install_pogcc_com_service.sh --enable-now"
    fi
    ;;
  *)
    echo "Unknown MODE=${MODE}" >&2
    exit 2
    ;;
esac
