@echo off
setlocal

set "RUN_NODE=auto"

call :run "git pull --ff-only" "Git pull"
call :run "composer install --no-interaction --no-dev --optimize-autoloader" "Composer install"
call :run "php artisan migrate --force" "Migrations"
call :run "php artisan config:cache" "Config cache"
call :run "php artisan route:cache" "Route cache"
call :run "php artisan view:cache" "View cache"
call :run "php artisan optimize" "Optimize"

if /i "%RUN_NODE%"=="1" goto :run_node
if /i "%RUN_NODE%"=="auto" goto :maybe_node
goto :done

:maybe_node
where npm >nul 2>nul
if errorlevel 1 goto :done

:run_node
if exist package-lock.json (
    call :run "npm ci" "NPM install"
) else (
    call :run "npm install" "NPM install"
)
call :run "npm run build" "NPM build"
goto :done

:run
set "CMD=%~1"
set "LABEL=%~2"
if "%LABEL%"=="" set "LABEL=%CMD%"
echo == %LABEL%
%CMD%
if errorlevel 1 (
    echo Command failed: %CMD%
    exit /b 1
)
exit /b 0

:done
echo Update complete.
