@echo off
rem EuroMedSoft launcher - starts local MariaDB if needed, then the app.
setlocal
set "APPDIR=%~dp0"

set "DATADIR=%LOCALAPPDATA%\EuroMedSoft"
if not exist "%DATADIR%" mkdir "%DATADIR%" >nul 2>&1

rem Already listening on 3306? Then skip DB startup.
netstat -an | findstr /C:":3306 " | findstr LISTENING >nul 2>&1
if not errorlevel 1 goto launch

rem Bundled portable MariaDB: initialize a private data directory on first run
rem (root password 'softlex' - matches the first-run wizard's prefill), then
rem start the server bound to this machine only.
if exist "%APPDIR%mariadb\bin\mysqld.exe" (
  if not exist "%DATADIR%\data" (
    echo First run: preparing the practice database engine...
    "%APPDIR%mariadb\bin\mariadb-install-db.exe" --datadir="%DATADIR%\data" --password=softlex >nul 2>&1
  )
  start "" /B "%APPDIR%mariadb\bin\mysqld.exe" --datadir="%DATADIR%\data" --bind-address=127.0.0.1 --port=3306 --console
  goto waitdb
)

rem No bundle: locate an installed mysqld on PATH or scoop.
set "MYSQLD="
if not defined MYSQLD for /f "delims=" %%I in ('where mysqld 2^>nul') do if not defined MYSQLD set "MYSQLD=%%I"
if not defined MYSQLD if exist "%LOCALAPPDATA%\..\scoop\shims\mysqld.exe" set "MYSQLD=%LOCALAPPDATA%\..\scoop\shims\mysqld.exe"

if not defined MYSQLD goto launch
start "" /B "%MYSQLD%"

rem Wait until the database accepts connections (max ~30s).
set /a tries=0
:waitdb
netstat -an | findstr /C:":3306 " | findstr LISTENING >nul 2>&1
if not errorlevel 1 goto launch
set /a tries+=1
if %tries% geq 30 goto launch
ping -n 2 127.0.0.1 >nul
goto waitdb

:launch
start "" "%APPDIR%EuroMedSoft.exe"
endlocal
