#!/usr/bin/env bash
set -euo pipefail

CONTAINER="hotel-mysql"
IMAGE="mysql:8.4"
ROOT_PASSWORD="hotel2025root"
DATABASE="hotel_reservations"
PORT="13306"

RUNTIME="docker"
if [[ "${1:-}" == "--podman" ]]; then
    RUNTIME="podman"
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SQL_DIR="$(cd "${SCRIPT_DIR}/../sql" && pwd)"

if ${RUNTIME} ps -a --format '{{.Names}}' | grep -q "^${CONTAINER}$"; then
    echo "Container '${CONTAINER}' already exists — starting it."
    ${RUNTIME} start "${CONTAINER}"
else
    echo "Creating and starting '${CONTAINER}' using ${RUNTIME}."
    ${RUNTIME} run -d \
        --name "${CONTAINER}" \
        -e MYSQL_ROOT_PASSWORD="${ROOT_PASSWORD}" \
        -e MYSQL_DATABASE="${DATABASE}" \
        -p "${PORT}:3306" \
        -v "${CONTAINER}-data:/var/lib/mysql" \
        -v "${SQL_DIR}/schema.sql:/docker-entrypoint-initdb.d/01_schema.sql:ro,z" \
        "${IMAGE}"
fi

echo "Waiting for MySQL to be ready..."
until ${RUNTIME} exec "${CONTAINER}" mysqladmin ping -uroot -p"${ROOT_PASSWORD}" --silent 2>/dev/null; do
    sleep 1
done

echo "MySQL 8.4 is up."
echo "  Host:     127.0.0.1:${PORT}"
echo "  Database: ${DATABASE}"
echo "  User:     root / ${ROOT_PASSWORD}"
