#!/usr/bin/env bash
set -e

EVENNIA=/root/wizards/bezalel/evennia/venv/bin/evennia
GAME=/root/wizards/bezalel/evennia/bezalel_world
PY=/root/wizards/bezalel/evennia/venv/bin/python

echo "=== Step 1: Add recursion fix to Evennia launcher ==="
# Add recursion limit right after the shebang
cd /root/wizards/bezalel/evennia/venv/bin
if ! grep -q "setrecursionlimit" evennia; then
    sed -i '2i import sys\nsys.setrecursionlimit(5000)' evennia
    echo "Fixed evennia launcher"
else
    echo "Already fixed"
fi

echo "=== Step 2: Run makemigrations ==="
cd "$GAME"
DJANGO_SETTINGS_MODULE=server.conf.settings $PY -c "
import sys
sys.setrecursionlimit(5000)
import django
django.setup()
from django.core.management import call_command
call_command('makemigrations', interactive=False)
" 2>&1 | tail -10

echo "=== Step 3: Run migrate ==="
DJANGO_SETTINGS_MODULE=server.conf.settings $PY -c "
import sys
sys.setrecursionlimit(5000)
import django
django.setup()
from django.core.management import call_command
call_command('migrate', interactive=False)
" 2>&1 | tail -5

echo "=== Step 4: Start Evennia ==="
$EVENNIA start 2>&1

echo "=== Waiting 5s ==="
sleep 5

echo "=== Status ==="
$EVENNIA status 2>&1

echo "=== Ports ==="
ss -tlnp 2>/dev/null | grep -E "4100|4101|4102" || echo "No Evennia ports yet"

echo "=== Processes ==="
ps aux | grep [t]wistd | head -3

echo "=== Server log ==="
tail -10 "$GAME/server/logs/server.log" 2>/dev/null

echo "=== DONE ==="
