#!/bin/bash
set -e

ROLE="$1"                     # login | game
DB_HOST="${DB_HOST:-db}"
DB_PASS="${DB_PASS:-l2j}"
DB_NAME="l2jmobiusinterlude"
FAKE_LLM_URL="${FAKE_LLM_URL:-http://host.docker.internal:11434/api/generate}"

M() { mariadb -h "$DB_HOST" -uroot -p"$DB_PASS" "$@"; }

# MOUNTED: файлы сервера примонтированы с диска, а не вшиты в образ.
echo "[entrypoint] waiting for database at $DB_HOST..."
until M -e "SELECT 1" >/dev/null 2>&1; do sleep 2; done

# Patch configs for the container network.
for f in /opt/l2/login/config/Database.ini /opt/l2/game/config/Database.ini; do
    sed -i "s|jdbc:mysql://localhost|jdbc:mysql://$DB_HOST|" "$f"
    sed -i "s|^Password *=.*|Password = $DB_PASS|" "$f"
done
sed -i "s|^LoginHostname *=.*|LoginHostname = 0.0.0.0|" /opt/l2/login/config/Server.ini
sed -i "s|^LoginHost *=.*|LoginHost = login|" /opt/l2/game/config/Server.ini
sed -i "s|^FakePlayerLlmUrl *=.*|FakePlayerLlmUrl = $FAKE_LLM_URL|" /opt/l2/game/config/Custom/FakePlayers.ini
# Client-facing IP: everything is published on localhost of the host machine.
cp -f /opt/l2/game/config/default-ipconfig.xml /opt/l2/game/config/ipconfig.xml

if [ "$ROLE" = "login" ]; then
    TABLES=$(M -N -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME'")
    if [ "$TABLES" -eq 0 ]; then
        echo "[entrypoint] empty database, importing sql..."
        for f in /opt/l2/db_installer/sql/login/*.sql /opt/l2/db_installer/sql/game/*.sql; do
            M "$DB_NAME" < "$f"
        done
        echo "[entrypoint] import done."
    fi
    for seed in /opt/l2/db_installer/sql/spp_*.sql; do
        [ -f "$seed" ] || continue
        M "$DB_NAME" < "$seed" && echo "[entrypoint] applied $(basename "$seed")"
    done
    cd /opt/l2/login
    exec java -Xmx256m -cp "../libs/*" org.l2jmobius.loginserver.LoginServer
fi

if [ "$ROLE" = "game" ]; then
    # Wait until login finished the import.
    until [ "$(M -N -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME'")" -gt 50 ]; do
        echo "[entrypoint] waiting for database schema..."
        sleep 3
    done
    cd /opt/l2/game
    exec java $(cat java.cfg) -cp "../libs/*" org.l2jmobius.gameserver.GameServer
fi

echo "Usage: entrypoint.sh login|game" >&2
exit 1
