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

cd /root/wizards/bezalel/evennia/bezalel_world

pkill -9 twistd 2>/dev/null || true
pkill -9 evennia 2>/dev/null || true
sleep 2

# Delete DB
rm -f server/evennia.db3

EVENNIA=/root/wizards/bezalel/evennia/venv/bin/evennia
TYPE_MIGRATIONS=/root/wizards/bezalel/evennia/venv/lib/python3.12/site-packages/evennia/typeclasses/migrations/

# Delete the problematic migration
rm -f ${TYPE_MIGRATIONS}*0018*
echo "Deleted 0018 migration"

# List remaining migrations
echo "Remaining typeclasses migrations:"
ls ${TYPE_MIGRATIONS}* 2>/dev/null | sort

# Try migrate
echo "=== Migrate ==="
$EVENNIA migrate 2>&1 | tail -10

echo "=== Start ==="
$EVENNIA start 2>&1 | tail -5

sleep 5

echo "=== Status ==="
$EVENNIA status 2>&1 || echo "status check failed"

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

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

echo "=== Log tail ==="
tail -10 server/logs/server.log 2>/dev/null || tail -10 server/logs/portal.log 2>/dev/null

echo "=== DONE ==="
