#!/usr/bin/env bash
# Rebuild and restart the stack with your latest changes.
#   ./build.sh             rebuild image + restart (DB data kept)
#   ./build.sh --reset-db  also wipe the DB so db/init.sql runs again
set -euo pipefail
cd "$(dirname "$0")"

# Docker Desktop not running? fall back to the system daemon
if ! docker info &>/dev/null; then
    export DOCKER_CONTEXT=default
    docker info &>/dev/null || { echo "Docker is not running"; exit 1; }
fi

if [[ "${1:-}" == "--reset-db" ]]; then
    echo ">> Removing containers and DB volume"
    docker compose down -v
fi

echo ">> Building and starting"
docker compose up -d --build --remove-orphans

echo ">> Waiting for MySQL"
for _ in $(seq 1 60); do
    if docker compose exec -T db mysqladmin ping -h127.0.0.1 -uadmin -ptest --silent &>/dev/null; then
        break
    fi
    sleep 1
done

docker compose ps
echo
echo "Site:       http://localhost   (or http://php.lab if set in /etc/hosts)"
echo "phpMyAdmin: http://localhost:8081   (admin / test)"
echo "App logins: usr / test (naudotojas), kon / test (konsultantas), admin / test (administratorius)"
