@echo off
:: Change to the directory where this batch file is located
cd /d "%~dp0"

:: Check for debug flag
set "DEBUG_FLAG="
if /i "%~1"=="-debug" set "DEBUG_FLAG=-Debug"
if /i "%~1"=="--debug" set "DEBUG_FLAG=-Debug"
if /i "%~1"=="/debug" set "DEBUG_FLAG=-Debug"

:: Check for internal elevated flag (used after copy operation)
set "ELEVATED_COPY="
if /i "%~2"=="__ELEVATED_COPY__" set "ELEVATED_COPY=1"

:: Ensure the script is running with administrative privileges
:: If not, copy files to a persistent temp location and request elevation
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo Requesting Administrator privileges...
    
    :: Create a persistent temp folder that won't be cleaned up during elevation
    set "PERSIST_DIR=%TEMP%\MarvellFWUpdate_%RANDOM%"
    
    :: Use PowerShell to copy files and launch elevated process from the new location
    powershell -ExecutionPolicy Bypass -NoProfile -Command ^
        "$persistDir = [System.IO.Path]::Combine($env:TEMP, 'MarvellFWUpdate_' + (Get-Random)); " ^
        "New-Item -ItemType Directory -Path $persistDir -Force | Out-Null; " ^
        "Copy-Item -Path '%~dp0*' -Destination $persistDir -Recurse -Force; " ^
        "$newBat = Join-Path $persistDir 'startprg.bat'; " ^
        "$argList = '/c \"\"' + $newBat + '\" %~1 __ELEVATED_COPY__\"'; " ^
        "Start-Process cmd -ArgumentList $argList -Verb RunAs -Wait; " ^
        "Remove-Item -Path $persistDir -Recurse -Force -ErrorAction SilentlyContinue"
    exit /b
)

:: If we're running from an elevated copy, display info
if defined ELEVATED_COPY (
    echo Running from secure temporary location...
)

echo Starting Firmware Update Process...
if defined DEBUG_FLAG echo [DEBUG MODE ENABLED]
echo.

:: Create Logs folder if it doesn't exist
if not exist "%~dp0Logs\" mkdir "%~dp0Logs"

:: Generate log file name with timestamp using PowerShell
for /f "delims=" %%i in ('powershell -Command "Get-Date -Format 'yyyyMMdd_HHmmss'"') do set timestamp=%%i
set "logfile=%~dp0Logs\FirmwareUpdate_%timestamp%.log"

:: Run the PowerShell script and capture output to both console and log file
powershell -ExecutionPolicy Bypass -NoProfile -Command "& '%~dp0flashUpdateScript.ps1' %DEBUG_FLAG% *>&1 | Tee-Object -FilePath '%logfile%'"