#!/usr/bin/env bash
# Install fixture-/dev-only inotify offload watcher (+ slow safety timer).
#
# Bench soak seats only. Hard-gated worker refuses /prod.
# Requires inotify-tools (installs via apt if missing and sudo available).
#
#   bash install_fixture_dev_rotated_offload.sh
#   bash install_fixture_dev_rotated_offload.sh --uninstall

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 [[ "$(id -un)" == root ]]; then
  echo "FATAL: run as topbox, not root." >&2
  exit 1
fi

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
USER_SYSTEMD="${HOME}/.config/systemd/user"
LOG_DIR="${HOME}/EtherGold/logs"
WATCH_UNIT="ethergold-fixture-dev-offload-watch"
SAFE_UNIT="ethergold-fixture-dev-offload-safety"
mkdir -p "${USER_SYSTEMD}" "${LOG_DIR}" "${HOME}/EtherGold/dev/data" "${HOME}/EtherGold/dev/logs"

if [[ -z "${XDG_RUNTIME_DIR:-}" ]]; then
  export XDG_RUNTIME_DIR="/run/user/$(id -u)"
fi
if [[ -z "${DBUS_SESSION_BUS_ADDRESS:-}" && -S "${XDG_RUNTIME_DIR}/bus" ]]; then
  export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"
fi

write_unit() {
  local name="$1"
  local body="$2"
  printf '%s\n' "${body}" > "${USER_SYSTEMD}/${name}"
}

if [[ "${1:-}" == "--uninstall" ]]; then
  systemctl --user disable --now "${WATCH_UNIT}.service" 2>/dev/null || true
  systemctl --user disable --now "${SAFE_UNIT}.timer" 2>/dev/null || true
  rm -f \
    "${USER_SYSTEMD}/${WATCH_UNIT}.service" \
    "${USER_SYSTEMD}/${SAFE_UNIT}.service" \
    "${USER_SYSTEMD}/${SAFE_UNIT}.timer"
  systemctl --user daemon-reload
  echo "Removed fixture-dev offload watch + safety timer."
  exit 0
fi

if ! command -v inotifywait >/dev/null 2>&1; then
  echo "inotifywait missing — installing inotify-tools…"
  if command -v sudo >/dev/null 2>&1; then
    sudo apt-get update -qq
    sudo apt-get install -y inotify-tools
  else
    echo "FATAL: install inotify-tools (need inotifywait); no sudo." >&2
    exit 1
  fi
fi
if ! command -v inotifywait >/dev/null 2>&1; then
  echo "FATAL: inotifywait still missing after apt." >&2
  exit 1
fi

chmod +x \
  "${ROOT}/offload_fixture_dev_rotated.sh" \
  "${ROOT}/watch_fixture_dev_rotated.sh" \
  2>/dev/null || true

write_unit "${WATCH_UNIT}.service" "[Unit]
Description=EtherGold fixture /dev — inotify offload rotated capture
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
WorkingDirectory=${ROOT}
ExecStart=/bin/bash ${ROOT}/watch_fixture_dev_rotated.sh
Restart=always
RestartSec=5
StandardOutput=append:${LOG_DIR}/.fixture_dev_offload_last.log
StandardError=append:${LOG_DIR}/.fixture_dev_offload_last.log

[Install]
WantedBy=default.target"

write_unit "${SAFE_UNIT}.service" "[Unit]
Description=EtherGold fixture /dev — safety offload rotated capture (oneshot)

[Service]
Type=oneshot
WorkingDirectory=${ROOT}
Environment=FIXTURE_DEV_OFFLOAD_TRUNCATE=0
ExecStart=/bin/bash ${ROOT}/offload_fixture_dev_rotated.sh
StandardOutput=append:${LOG_DIR}/.fixture_dev_offload_last.log
StandardError=append:${LOG_DIR}/.fixture_dev_offload_last.log"

write_unit "${SAFE_UNIT}.timer" "[Unit]
Description=Every ~30 min: fixture /dev rotated offload safety net

[Timer]
OnBootSec=5min
OnUnitActiveSec=30min
AccuracySec=1min
Persistent=true
Unit=${SAFE_UNIT}.service

[Install]
WantedBy=timers.target"

systemctl --user daemon-reload
systemctl --user enable --now "${WATCH_UNIT}.service"
systemctl --user enable --now "${SAFE_UNIT}.timer"

echo "Installed fixture-/dev rotated offload:"
echo "  ${WATCH_UNIT}.service  (inotify watch)"
echo "  ${SAFE_UNIT}.timer     (30 min safety)"
echo "  systemctl --user status ${WATCH_UNIT}.service"
echo "  DRY_RUN=1 bash ${ROOT}/offload_fixture_dev_rotated.sh"
if [[ ! -f "${ROOT}/rclone.env" ]]; then
  echo "NOTE: ${ROOT}/rclone.env missing — watcher runs but offload no-ops until configured."
fi
echo "Scope: ONLY ~/EtherGold/dev/{data,logs} — not /prod."
