#!/bin/bash
set -euo pipefail

IMAGE=gitea.earthmanrpg.me/discoman/gamearray:latest

echo "==> Pulling latest image..."
docker pull "$IMAGE"

echo "==> Stopping old container..."
docker stop gamearray 2>/dev/null || true
docker rm gamearray 2>/dev/null || true

echo "==> Starting new container..."
docker run -d --name gamearray \
    --restart unless-stopped \
    --env-file /opt/gamearray/gamearray.env \
    --network gamearray_net \
    -p 127.0.0.1:8888:8888 \
    "$IMAGE"

echo "==> Stopping old celery worker..."
docker stop gamearray_celery 2>/dev/null || true
docker rm gamearray_celery 2>/dev/null || true

echo "==> Starting new celery worker..."
docker run -d --name gamearray_celery \
    --restart unless-stopped \
    --env-file /opt/gamearray/gamearray.env \
    --network gamearray_net \
    "$IMAGE" python -m celery -A core worker -l info

echo "==> Running migrations..."
docker exec gamearray python ./manage.py migrate

echo "==> Ensuring superuser exists..."
docker exec gamearray python manage.py ensure_superuser

echo "==> Copying static files..."
sudo docker cp gamearray:/src/static/. /var/www/gamearray/static/

echo "==> Deploy complete."