@echo off
setlocal EnableDelayedExpansion
title ATAPOLY CBT INSTALLER

set PORT=3001
set "DOCKER_PATH=C:\Program Files\Docker\Docker\Docker Desktop.exe"
set "DOCKER_INSTALLER=%~dp0Docker Desktop Installer.exe"

cls

echo.
echo  ==========================================
echo            ATAPOLY CBT INSTALLER
echo  ==========================================
echo.

set /p confirm=Proceed installation (Y/N): 
if /I not "%confirm%"=="Y" exit

echo.
echo  [1/5] Checking Docker environment...
echo ------------------------------------------

docker version >nul 2>&1
if errorlevel 1 (
    echo Docker not found or not running.

    if exist "%DOCKER_PATH%" (
        echo Starting Docker Desktop...
        start "" "%DOCKER_PATH%"
    ) else (
        echo Installing Docker from local setup...
        start /wait "" "%DOCKER_INSTALLER%" /quiet
    )

    call :WAIT_DOCKER
)

echo Docker is ready.

echo.
echo  [2/5] Checking application images...
echo ------------------------------------------

docker images | findstr atapoly-cbt-app >nul
if errorlevel 1 (
    echo Loading application image...
    docker load -i atapoly-cbt-images.tar >nul
)

echo.
echo  [3/5] Starting system services...
echo ------------------------------------------

docker compose up -d >nul

if errorlevel 1 (
    echo ERROR: Failed to start services
    pause
    exit
)

echo Services started successfully.

timeout /t 3 >nul

echo.
echo  [4/5] Detecting network settings...
echo ------------------------------------------

for /f "tokens=2 delims=:" %%f in ('ipconfig ^| findstr IPv4') do (
    set ip=%%f
    goto ipdone
)

:ipdone
set ip=%ip: =%

echo.
echo  [5/5] Finalizing installation...
echo ------------------------------------------

echo.
echo  ==========================================
echo            INSTALLATION COMPLETE
echo  ==========================================
echo.
echo  Local Access  : http://localhost:%PORT%
echo  Network Access: http://%ip%:%PORT%
echo.
echo  Opening application...
echo  All set, you can now close this.

start http://localhost:%PORT%

pause
exit /b


:: ==========================================
:: CLEAN PROGRESS BAR (FIXED UI)
:: ==========================================
:WAIT_DOCKER
setlocal EnableDelayedExpansion

set /a max=20

echo.
echo  Preparing Docker Engine...
echo ------------------------------------------

for /l %%i in (1,1,%max%) do (

    docker version >nul 2>&1
    if not errorlevel 1 (
        goto ready
    )

    set "bar="
    for /l %%j in (1,1,%%i) do set "bar=!bar!#"

    set /a empty=%max%-%%i
    set "space="
    for /l %%k in (1,1,!empty!) do set "space=!space! "

    <nul set /p="  [!bar!!space!] %%i/%max%"

    timeout /t 1 >nul
    echo.
)

:ready
echo.
echo  Docker engine ready.
endlocal
exit /b