#!/usr/bin/env bash
# User systemd timers: hourly EtherGold stage, 03:00 promote.
# OTA_CHANNEL=dev: promote_staging.sh skips the 03:00 auto-promote (workshop /dev
# tip) unless FORCE=1 / Update Now — stage still runs hourly into Staging.
#
#   bash install_pi_deploy_schedule.sh
#   bash install_pi_deploy_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"
mkdir -p "${USER_SYSTEMD}" "${LOG_DIR}"

# runuser/HTTP Update Now has no login session; user systemd needs these.
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 ethergold-stage.timer ethergold-promote.timer 2>/dev/null || true
  rm -f \
    "${USER_SYSTEMD}/ethergold-stage.service" \
    "${USER_SYSTEMD}/ethergold-stage.timer" \
    "${USER_SYSTEMD}/ethergold-promote.service" \
    "${USER_SYSTEMD}/ethergold-promote.timer"
  systemctl --user daemon-reload
  echo "Removed EtherGold deploy timers."
  exit 0
fi

write_unit "ethergold-stage.service" "[Unit]
Description=EtherGold — stage from Dropbox SGVI (incremental)

[Service]
Type=oneshot
WorkingDirectory=${ROOT}
Environment=QUIET=1
Environment=LOG_OFFLOAD_PRODUCT=ethergold
ExecStart=/bin/bash ${ROOT}/stage_from_dropbox.sh
StandardOutput=append:${LOG_DIR}/stage.log
StandardError=append:${LOG_DIR}/stage.log"

write_unit "ethergold-stage.timer" "[Unit]
Description=Hourly EtherGold staging from Dropbox SGVI

[Timer]
OnCalendar=hourly
Persistent=true
Unit=ethergold-stage.service

[Install]
WantedBy=timers.target"

write_unit "ethergold-promote.service" "[Unit]
Description=EtherGold — promote staging at 03:00 America/St_Thomas

[Service]
Type=oneshot
WorkingDirectory=${ROOT}
Environment=PROMOTE_RESTART=1
ExecStart=/bin/bash -c 'S=${HOME}/EtherGold-Staging/sync/promote_staging.sh; L=${HOME}/EtherGold/sync/promote_staging.sh; if [ -f \"\$S\" ]; then exec /bin/bash \"\$S\"; else exec /bin/bash \"\$L\"; fi'
StandardOutput=append:${LOG_DIR}/promote.log
StandardError=append:${LOG_DIR}/promote.log"

write_unit "ethergold-promote.timer" "[Unit]
Description=Daily 03:00 America/St_Thomas EtherGold promote (if staging-pending)

[Timer]
OnCalendar=*-*-* 03:00:00
Timezone=America/St_Thomas
Persistent=true
Unit=ethergold-promote.service

[Install]
WantedBy=timers.target"

systemctl --user daemon-reload
systemctl --user enable --now ethergold-stage.timer ethergold-promote.timer

echo "Enabled:"
systemctl --user list-timers 'ethergold-*' --no-pager || true
echo ""
echo "Logs: ${LOG_DIR}/stage.log  ${LOG_DIR}/promote.log"
echo ""
if ! loginctl show-user "$(id -un)" -p Linger 2>/dev/null | grep -q 'Linger=yes'; then
  if sudo -n loginctl enable-linger "$(id -un)" 2>/dev/null; then
    echo "linger enabled for $(id -un)"
  else
    echo "IMPORTANT — run once as root so timers work without desktop login:"
    echo "  sudo loginctl enable-linger $(id -un)"
  fi
fi

if [[ -f "${ROOT}/install_hs_out_idle.sh" ]]; then
  bash "${ROOT}/install_hs_out_idle.sh" || echo "WARN: HS OUT idle not installed (need sudo -n)" >&2
fi
