@echo off
setlocal EnableDelayedExpansion
title ATAPOLY CBT Uninstaller

set "DOCKER_PATH=C:\Program Files\Docker\Docker\Docker Desktop.exe"

cls

echo.
echo  ==========================================
echo        ATAPOLY CBT SYSTEM UNINSTALLER
echo  ==========================================
echo.

set /p confirm=This will remove ALL system components. Continue (Y/N): 
if /I not "%confirm%"=="Y" exit

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

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

    if exist "%DOCKER_PATH%" (
        echo Starting Docker Desktop...
        start "" "%DOCKER_PATH%"
        call :WAIT_DOCKER
    ) else (
        echo WARNING: Docker not found.
        echo Some cleanup steps may fail.
    )
) else (
    echo Docker is already running.
)

echo.
echo  [2/4] Stopping system containers...
echo ------------------------------------------

docker compose down -v >nul 2>&1

timeout /t 2 >nul

echo.
echo  [3/4] Removing application images...
echo ------------------------------------------

docker rmi atapoly-cbt-app:latest >nul 2>&1
docker rmi postgres:15-alpine >nul 2>&1
docker rmi postgres:15 >nul 2>&1

timeout /t 2 >nul

echo.
echo  [4/4] Cleaning Docker system resources...
echo ------------------------------------------

docker system prune -f >nul 2>&1

timeout /t 2 >nul

echo.
echo  ==========================================
echo        UNINSTALL COMPLETED SUCCESSFULLY
echo  ==========================================
echo.
echo  All ATAPOLY CBT components have been removed.
echo.

pause
exit /b


:: ==========================================
:: CLEAN DOCKER WAIT PROGRESS BAR
:: ==========================================
: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%"
    echo.

    timeout /t 1 >nul
)

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