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

cd /root/wizards/bezalel/evennia/bezalel_world

# Kill everything
pkill -9 twistd 2>/dev/null || true
pkill -9 evennia 2>/dev/null || true
sleep 3

EVENNIA=/root/wizards/bezalel/evennia/venv/bin/evennia

# Ensure DB is clean
rm -f server/evennia.db3

# Create superuser non-interactively
echo "=== Creating superuser ==="
$EVENNIA -v=1 migrate
echo "from evennia.accounts.accounts import AccountDB; AccountDB.objects.create_superuser('Timmy','timmy@timmy.com','timmy123')" | $EVENNIA shell -c "-"

# Start in background
echo "=== Starting Evennia ==="
$EVENNIA start

# Wait and check
sleep 5

# Try connecting
echo "=== Telnet test ==="
echo "" | nc -w 3 127.0.0.1 4000 2>&1 | head -5 || echo "telnet 4000: no response"

echo "=== Status ==="
ps aux | grep [t]wistd | head -3
ss -tlnp 2>/dev/null | grep -E "400[0-2]|410[0-2]" || echo "No Evennia ports"
tail -10 server/logs/server.log 2>/dev/null
tail -10 server/logs/portal.log 2>/dev/null
