#!/usr/bin/env bash
# Container entrypoint: restore the DB from B2 on an empty volume, then run cron under litestream.
set -euo pipefail
mkdir -p /data/scout /data/repos /data/scout/logs
export SCOUT_DATA_DIR=/data/scout SCOUT_REPO_ROOT=/data/repos SCOUT_CLOUD=1
git config --global user.name "Feature Scout"
git config --global user.email "${SCOUT_GIT_EMAIL:-feature-scout@localhost}"   # a Fly secret, not in this file
git config --global --add safe.directory '*'

if [ "${1:-cron}" != "cron" ]; then
  exec "$@"            # one-off: `fly ssh console -C "/app/cloud/entrypoint.sh scout status"`
fi

DB=/data/scout/scout.sqlite
if [ ! -f "$DB" ] && [ -n "${LITESTREAM_REPLICA_BUCKET:-}" ]; then
  echo "[entrypoint] no DB on the volume; trying a restore from B2"
  litestream restore -if-replica-exists -config /app/litestream.yml "$DB" || echo "[entrypoint] nothing to restore"
fi
# The review page: the same page a person gets on their own computer, served here behind the
# private link. It must start after the restore above, or on a fresh volume it would open an
# empty database and leave nothing for litestream to restore into. No secret, no page.
if [ -n "${SCOUT_REVIEW_TOKEN:-}" ]; then
  echo "[entrypoint] starting the review page"
  # Kept alive: if it ever falls over, the page comes back rather than quietly vanishing.
  ( while true; do
      scout review --serve >> /data/scout/logs/review.log 2>&1
      echo "[review] stopped; starting again in 10s" >> /data/scout/logs/review.log
      sleep 10
    done ) &
fi

if [ -n "${LITESTREAM_REPLICA_BUCKET:-}" ]; then
  exec litestream replicate -config /app/litestream.yml -exec "supercronic -passthrough-logs /app/cloud/crontab"
fi
exec supercronic -passthrough-logs /app/cloud/crontab
