#!/usr/bin/env bash
# Ship-time DyzineFrame file seed — stage from Dropbox, promote to live, install timers.
# Does NOT restart the display (no SSH runit / supervisor launch).
#
#   bash ~/DyzineFrame/sync/seed_from_dropbox.sh
#
# Used by prepare_listen_stock.sh so Michigan / field TopBox stock leaves with
# the current SGVI/DyzineFrame tree (not whatever leftover version was on the card).

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: do not run as root. Use: sudo -u topbox bash $0" >&2
  exit 1
fi

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=dyzineframe_paths.sh
source "${ROOT}/dyzineframe_paths.sh"

if [[ ! -f "${ROOT}/stage_from_dropbox.sh" ]]; then
  echo "FATAL: missing ${ROOT}/stage_from_dropbox.sh" >&2
  exit 1
fi

echo "=== seed_from_dropbox (stage + promote, no display restart) ==="

# First stage may still use the old To Deploy rclone path; that pull also
# refreshes sync/dropbox_paths.sh to SGVI/DyzineFrame. Stage again so the
# live tree matches the production object.
bash "${ROOT}/stage_from_dropbox.sh"
bash "${ROOT}/stage_from_dropbox.sh"

FORCE=1 PROMOTE_RESTART=0 bash "${ROOT}/promote_staging.sh"

if [[ -f "${ROOT}/install_pi_deploy_schedule.sh" ]]; then
  bash "${ROOT}/install_pi_deploy_schedule.sh" || {
    echo "WARN: install_pi_deploy_schedule.sh failed (need linger + systemd --user)" >&2
  }
fi

# Boot via DyzineFrame Supervisor (crash reload). Do not launch the display over SSH.
if [[ -f "${DYZINEFRAME_ROOT}/topboxboot.desktop" ]]; then
  mkdir -p "${HOME}/.config/autostart"
  cp -f "${DYZINEFRAME_ROOT}/topboxboot.desktop" "${HOME}/.config/autostart/topboxboot.desktop"
  chmod +x "${DYZINEFRAME_ROOT}/run_supervisor.sh" 2>/dev/null || true
  echo "autostart: ${HOME}/.config/autostart/topboxboot.desktop -> run_supervisor.sh"
else
  echo "WARN: missing ${DYZINEFRAME_ROOT}/topboxboot.desktop — autostart not restored" >&2
fi

echo ""
echo "seed_from_dropbox ok"
if [[ -f "${DYZINEFRAME_ROOT}/VERSION.txt" ]]; then
  echo "Live VERSION: $(cat "${DYZINEFRAME_ROOT}/VERSION.txt")"
fi
echo "Display: restart from Pi desktop or next boot (not SSH)."
