@echo off
setlocal enabledelayedexpansion

REM Carica le variabili d'ambiente dal file .env
if exist .env (
    for /f "usebackq tokens=*" %%i in (.env) do (
        set %%i
    )
) else (
    echo .env file not found. Please create one with UPDATE_TIME and JBOSS_HOME variables.
    exit /b 1
)

REM Controlla se le variabili d'ambiente richieste sono impostate
if not defined JBOSS_HOME (
    echo JBOSS_HOME is not set. Please check your .env file.
    exit /b 1
)
if not defined UPDATE_TIME (
    echo UPDATE_TIME is not set. Please check your .env file.
    exit /b 1
)

rem war folder
set "SOURCE_DIR=..\..\stub-war\target"

rem jboss deployment
set "DEST_DIR=%JBOSS_HOME%\standalone\deployments"

rem Imposta UPDATE_TIME come intero
set /a "UPDATE_TIME=%UPDATE_TIME%"

rem war to monitor
set "FILE_TO_MONITOR=stub-war.war"

echo Controllo esistenza delle directory...
if not defined DEST_DIR (
    echo DEST_DIR non esiste: %DEST_DIR%
    exit /b 1
)
if not defined SOURCE_DIR (
    echo %~dp0
    echo SOURCE_DIR non esiste: %SOURCE_DIR%
    exit /b 1
)

rem Ottieni la data di modifica iniziale del file
set LAST_COPY_TIME=""
:loop
    rem Ottieni la data di modifica attuale del file
    for %%F in ("%SOURCE_DIR%\%FILE_TO_MONITOR%") do set CURRENT_LAST_EDIT_FILE_TIME=%%~tF

    rem Confronta le date di modifica
    if not "!CURRENT_LAST_EDIT_FILE_TIME!"=="!LAST_COPY_TIME!" (
        echo CURRENT_LAST_EDIT_FILE_TIME = !CURRENT_LAST_EDIT_FILE_TIME!
        rem Sposta il file se è stato modificato
        copy "%SOURCE_DIR%\%FILE_TO_MONITOR%" "%DEST_DIR%\"
        rem Aggiorna la data di modifica
        set LAST_COPY_TIME=!CURRENT_LAST_EDIT_FILE_TIME!
        echo LAST_COPY_TIME = !LAST_COPY_TIME!
    )

    timeout /t %UPDATE_TIME% >nul
goto loop