#!/usr/bin/env bash
# User systemd timer: offload rotated luxury capture every ~10 minutes.
#
# Bench / soak seats only — not required for field prod.
# Safe to install even if rclone.env is missing (offload script no-ops).
#
#   bash install_offload_rotated_capture_schedule.sh
#   bash install_offload_rotated_capture_schedule.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"
UNIT_BASE="ethergold-offload-rotated"
mkdir -p "${USER_SYSTEMD}" "${LOG_DIR}"

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 "${UNIT_BASE}.timer" 2>/dev/null || true
  rm -f \
    "${USER_SYSTEMD}/${UNIT_BASE}.service" \
    "${USER_SYSTEMD}/${UNIT_BASE}.timer"
  systemctl --user daemon-reload
  echo "Removed ${UNIT_BASE} timer."
  exit 0
fi

write_unit "${UNIT_BASE}.service" "[Unit]
Description=EtherGold — rclone offload rotated capture (events.jsonl.* etc.)

[Service]
Type=oneshot
WorkingDirectory=${ROOT}
ExecStart=/bin/bash ${ROOT}/offload_rotated_capture.sh
StandardOutput=append:${LOG_DIR}/.offload_rotated_last.log
StandardError=append:${LOG_DIR}/.offload_rotated_last.log"

write_unit "${UNIT_BASE}.timer" "[Unit]
Description=Every ~10 min: offload rotated luxury capture to Dropbox

[Timer]
OnBootSec=3min
OnUnitActiveSec=10min
AccuracySec=1min
Persistent=true
Unit=${UNIT_BASE}.service

[Install]
WantedBy=timers.target"

systemctl --user daemon-reload
systemctl --user enable --now "${UNIT_BASE}.timer"
echo "Installed ${UNIT_BASE}.timer (OnUnitActiveSec=10min)."
echo "  systemctl --user status ${UNIT_BASE}.timer"
echo "  DRY_RUN=1 bash ${ROOT}/offload_rotated_capture.sh"
if [[ ! -f "${ROOT}/rclone.env" ]]; then
  echo "NOTE: ${ROOT}/rclone.env missing — timer runs but offload no-ops until configured."
fi
