@echo off
REM ============================================================
REM  findvc.bat - locate the x64 MSVC build environment.
REM
REM  Sets VCVARS to a vcvars64.bat and exits 0, or explains how to
REM  fix it and exits 1. Called by the build_*.bat scripts.
REM
REM  Order: VCVARS already set by the caller  >  vswhere (any
REM  installed edition/year)  >  well-known install paths.
REM  Deliberately NOT pinned to one Visual Studio year - hardcoding
REM  a year is what breaks these scripts on a different machine.
REM ============================================================
if defined VCVARS if exist "%VCVARS%" exit /b 0

set "VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
if not exist "%VSWHERE%" set "VSWHERE=%ProgramFiles%\Microsoft Visual Studio\Installer\vswhere.exe"

if exist "%VSWHERE%" (
  for /f "usebackq tokens=*" %%i in (`"%VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2^>nul`) do (
    if exist "%%i\VC\Auxiliary\Build\vcvars64.bat" set "VCVARS=%%i\VC\Auxiliary\Build\vcvars64.bat"
  )
)
if defined VCVARS if exist "%VCVARS%" exit /b 0

for %%E in (Community Professional Enterprise BuildTools) do (
  for %%Y in (18 2022 2019 2017) do (
    if exist "%ProgramFiles%\Microsoft Visual Studio\%%Y\%%E\VC\Auxiliary\Build\vcvars64.bat" (
      set "VCVARS=%ProgramFiles%\Microsoft Visual Studio\%%Y\%%E\VC\Auxiliary\Build\vcvars64.bat"
    )
    if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\%%Y\%%E\VC\Auxiliary\Build\vcvars64.bat" (
      set "VCVARS=%ProgramFiles(x86)%\Microsoft Visual Studio\%%Y\%%E\VC\Auxiliary\Build\vcvars64.bat"
    )
  )
)
if defined VCVARS if exist "%VCVARS%" exit /b 0

echo.
echo   Could not find the x64 MSVC build tools (vcvars64.bat).
echo.
echo   Install "Desktop development with C++" from the Visual Studio
echo   Installer, or set VCVARS yourself before running this script:
echo.
echo       set "VCVARS=C:\path\to\VC\Auxiliary\Build\vcvars64.bat"
echo.
exit /b 1
