#!/bin/sh
# Production entrypoint. Migrations run here rather than in Fly's release_command,
# because release machines don't mount the volume that holds the SQLite database.
set -eu

# The volume is mounted owned by root. Take ownership for the app user, then rerun as it.
if [ "$(id -u)" = 0 ]; then
  mkdir -p "${INTENT_DATA_DIR:?}"
  chown -R app:app "$INTENT_DATA_DIR"
  exec setpriv --reuid=app --regid=app --init-groups env HOME=/home/app "$0" "$@"
fi

DB="${INTENT_DATA_DIR:?}/db.sqlite3"
SERVER="gunicorn config.wsgi --bind 0.0.0.0:8000 --workers 3 --access-logfile -"

if [ -z "${LITESTREAM_BUCKET:-}" ]; then
  echo "LITESTREAM_BUCKET not set: running without backups" >&2
  python manage.py migrate --noinput
  python manage.py createcachetable
  exec $SERVER
fi

# On a fresh volume, pull the latest backup before anything touches the database.
litestream restore -if-db-not-exists -if-replica-exists "$DB"
python manage.py migrate --noinput
python manage.py createcachetable
exec litestream replicate -exec "$SERVER"
