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

MYSQL_DATA=/home/runner/mysql-data
MYSQL_RUN=/home/runner/mysql-run
MYSQL_SOCK=$MYSQL_RUN/mysql.sock

mkdir -p "$MYSQL_DATA" "$MYSQL_RUN"

# ── Init data dir if first run ─────────────────────────────
if [ ! -f "$MYSQL_DATA/ibdata1" ]; then
    echo "[start.sh] Initialising MariaDB data directory..."
    mysql_install_db --datadir="$MYSQL_DATA" \
                     --auth-root-authentication-method=normal \
                     --skip-test-db 2>&1 | tail -3
fi

# ── Start MariaDB in background ────────────────────────────
echo "[start.sh] Starting MariaDB..."
mysqld --datadir="$MYSQL_DATA" \
       --socket="$MYSQL_SOCK" \
       --pid-file="$MYSQL_RUN/mysql.pid" \
       --port=3306 \
       --bind-address=127.0.0.1 \
       --skip-networking=0 \
       --user=runner \
       --innodb-use-native-aio=0 \
       --log-error="$MYSQL_RUN/mysql-error.log" &

MYSQLD_PID=$!

# ── Wait until socket is ready (up to 30 s) ───────────────
echo "[start.sh] Waiting for MariaDB socket..."
for i in $(seq 1 30); do
    if mysqladmin --socket="$MYSQL_SOCK" -u root ping --silent 2>/dev/null; then
        echo "[start.sh] MariaDB ready."
        break
    fi
    sleep 1
done

# ── One-time DB + user + schema setup ─────────────────────
mysql --socket="$MYSQL_SOCK" -u root <<'SQL'
CREATE DATABASE IF NOT EXISTS weaversm CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS 'weaverdev'@'localhost' IDENTIFIED BY 'WeaverDev1!';
GRANT ALL PRIVILEGES ON weaversm.* TO 'weaverdev'@'localhost';
FLUSH PRIVILEGES;
SQL

# Import schema if users table doesn't exist yet
TABLE_EXISTS=$(mysql --socket="$MYSQL_SOCK" -u root weaversm -sse \
    "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='weaversm' AND table_name='users';" 2>/dev/null || echo 0)

if [ "$TABLE_EXISTS" = "0" ]; then
    echo "[start.sh] Importing schema..."
    mysql --socket="$MYSQL_SOCK" -u root weaversm < database/weaversm.sql
    echo "[start.sh] Schema imported."
fi

# ── Start PHP dev server (foreground — keeps workflow alive) 
echo "[start.sh] Starting PHP server on :5000..."
exec php -S 0.0.0.0:5000 router.php
