@echo off
setlocal EnableExtensions

set "SCRIPT_DIR=%~dp0"
set "DOWNLOAD_URL=https://solo.o-range.golf/download.php?file=legacy-export-upload.ps1&t=%RANDOM%%RANDOM%"

set "RUN_DIR=%SCRIPT_DIR%"
if "%RUN_DIR:~0,2%"=="\\" set "RUN_DIR=%TEMP%\solo-onboard"
if not exist "%RUN_DIR%" mkdir "%RUN_DIR%"

set "PS_SCRIPT=%RUN_DIR%\legacy-export-upload.ps1"

echo Downloading latest onboarding script...
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "$ProgressPreference='SilentlyContinue';try{$all=[System.Net.SecurityProtocolType]::Tls;if([Enum]::GetNames([System.Net.SecurityProtocolType]) -contains 'Tls11'){$all=$all -bor [System.Net.SecurityProtocolType]::Tls11};if([Enum]::GetNames([System.Net.SecurityProtocolType]) -contains 'Tls12'){$all=$all -bor [System.Net.SecurityProtocolType]::Tls12};[System.Net.ServicePointManager]::SecurityProtocol=$all;[System.Net.ServicePointManager]::Expect100Continue=$false}catch{};(New-Object System.Net.WebClient).DownloadFile('%DOWNLOAD_URL%','%PS_SCRIPT%')"
if errorlevel 1 (
  echo ERROR: Could not download latest live script from:
  echo %DOWNLOAD_URL%
  echo If this is Windows 7, install TLS 1.2 updates and .NET 4.6+.
  pause
  exit /b 1
)

if not exist "%PS_SCRIPT%" (
  echo ERROR: Could not download or locate legacy-export-upload.ps1.
  pause
  exit /b 1
)

if "%RUN_DIR:~0,2%"=="\\" (
  if /I not "%PS_SCRIPT%"=="%RUN_DIR%\legacy-export-upload.ps1" (
    copy /Y "%PS_SCRIPT%" "%RUN_DIR%\legacy-export-upload.ps1" >nul
    if errorlevel 1 (
      echo ERROR: Failed to stage script locally from UNC path.
      pause
      exit /b 1
    )
    set "PS_SCRIPT=%RUN_DIR%\legacy-export-upload.ps1"
  )
)

if not exist "%PS_SCRIPT%" (
  echo ERROR: Staged script missing: %PS_SCRIPT%
  pause
  exit /b 1
)

set "DID_PUSHD=0"
pushd "%RUN_DIR%" >nul 2>&1
if "%ERRORLEVEL%"=="0" set "DID_PUSHD=1"

echo Starting SOLO legacy export in PowerShell...
powershell.exe -NoLogo -NoExit -ExecutionPolicy Bypass -File "%PS_SCRIPT%" %*
set "RC=%ERRORLEVEL%"

if "%DID_PUSHD%"=="1" popd >nul 2>&1
exit /b %RC%
