#!/usr/bin/env bash
# A disposable, task-owned MySQL server. Never uses application DB credentials.
set -euo pipefail
cd "$(dirname "$0")/.."
container=mfuko-accounting-mysql
image=mysql:8.4@sha256:76f0358884cb92d9a086d24e5671c38048d3fef40f2588703d73eb55392d6b69
label=com.nugsoft.mfuko.accounting-test

owned_container() {
    local owner
    owner=$(docker inspect --format '{{ index .Config.Labels "com.nugsoft.mfuko.accounting-test" }}' "$container")
    if [ "$owner" != true ]; then
        echo 'Refusing to use/remove a container without the accounting-test ownership label.' >&2
        exit 1
    fi
}

case "${1:-test}" in
    stop)
        if docker container inspect "$container" >/dev/null 2>&1; then
            owned_container
            docker rm -f "$container" >/dev/null
        fi
        exit 0
        ;;
    start|test) ;;
    *) echo 'Usage: bash scripts/accounting-mysql.sh [start|test|stop]' >&2; exit 2 ;;
esac

if docker container inspect "$container" >/dev/null 2>&1; then
    owned_container
    docker start "$container" >/dev/null
else
    docker run -d --name "$container" --label "$label=true" \
        --tmpfs /var/lib/mysql:rw,size=1073741824 \
        -e MYSQL_DATABASE=mfuko_accounting_test \
        -e MYSQL_USER=accounting_test \
        -e MYSQL_PASSWORD=accounting_test_only \
        -e MYSQL_ROOT_PASSWORD=accounting_root_test_only \
        -p 127.0.0.1::3306 "$image" >/dev/null
fi

ready=false
for ((attempt=0; attempt<60; attempt++)); do
    if docker exec "$container" mysql --protocol=TCP -h127.0.0.1 \
        -uaccounting_test -paccounting_test_only mfuko_accounting_test \
        -N -e 'SELECT 1' >/dev/null 2>&1; then
        ready=true
        break
    fi
    sleep 1
done
if [ "$ready" != true ]; then
    echo 'Accounting MySQL did not become ready within 60 seconds.' >&2
    exit 1
fi
port=$(docker port "$container" 3306/tcp | awk -F: 'NR == 1 { print $NF }')
# Migrations use accounting_test; direct-SQL guard tests use only this DML role.
docker exec "$container" mysql -uroot -paccounting_root_test_only -e \
    "SET GLOBAL log_bin_trust_function_creators = 1; CREATE USER IF NOT EXISTS 'accounting_writer'@'%' IDENTIFIED BY 'accounting_writer_test_only'; GRANT SELECT, INSERT, UPDATE, DELETE ON mfuko_accounting_test.* TO 'accounting_writer'@'%';" 2>/dev/null
echo "Accounting MySQL ready on 127.0.0.1:$port (dedicated test database)."
if [ "${1:-test}" = test ]; then
    ACCOUNTING_MYSQL_HOST=127.0.0.1 \
    ACCOUNTING_MYSQL_PORT="$port" \
    ACCOUNTING_MYSQL_DATABASE=mfuko_accounting_test \
    ACCOUNTING_MYSQL_USERNAME=accounting_test \
    ACCOUNTING_MYSQL_PASSWORD=accounting_test_only \
        php vendor/bin/pest --configuration=phpunit.mysql.xml
fi
