@Rem Copyright Epic Games, Inc. All Rights Reserved.

@echo off

@Rem Set script location as working directory for commands.
pushd "%~dp0"

@Rem Name and version of node that we are downloading
SET NodeVersion=v16.4.2
SET NodeName=node-%NodeVersion%-win-x64

@Rem Pre-staged cache location on the runner. Overridable via NODE_CACHE_DIR env var.
if not defined NODE_CACHE_DIR set "NODE_CACHE_DIR=C:\BuildCache\node"

@Rem Look for a node directory next to this script
if exist node\ (
  echo Node directory found...skipping install.
) else (
  @Rem Preferred path: copy from a pre-staged cache on the runner. Avoids the
  @Rem download/extract/rename race entirely.
  if exist "%NODE_CACHE_DIR%\node.exe" (
    echo Copying node from cache: %NODE_CACHE_DIR%
    robocopy "%NODE_CACHE_DIR%" "node" /E /NFL /NDL /NJH /NJS /NP >nul
    if errorlevel 8 (
      echo WARNING: robocopy from cache failed, falling back to download.
      if exist node\ rmdir /S /Q node
    )
  )
)

@Rem Fallback path: download, extract, and rename if cache copy didn't succeed.
if not exist node\ (
  if exist "%NodeName%\" (
    echo Found %NodeName% directory, reusing existing extraction.
  ) else (
    echo Node directory not found...beginning NodeJS download for Windows.

    @Rem Download nodejs and follow redirects.
    curl -L -o ./node.zip "https://nodejs.org/dist/%NodeVersion%/%NodeName%.zip"

    @Rem Unarchive the .zip
    tar -xf node.zip

    @Rem Delete the downloaded node.zip
    del node.zip
  )

  @Rem Clear read-only attributes that can come from zip extraction and trip up the rename.
  attrib -R /S /D "%NodeName%\*" >nul 2>&1

  @Rem Use 'move' instead of 'ren' — it's more tolerant of transient locks (AV/indexer)
  @Rem and gives a clearer error if the target somehow already exists. Retry a few times
  @Rem with a delay to ride out Defender/indexer scans of the freshly-extracted files.
  set RenameAttempts=3
  set RenameDelay=10
  for /L %%i in (1,1,%RenameAttempts%) do (
    if not exist node\ (
      if %%i GTR 1 (
        echo Rename attempt %%i of %RenameAttempts% after %RenameDelay%s delay...
        timeout /t %RenameDelay% /nobreak >nul
      )
      move "%NodeName%" "node"
    )
  )

  if not exist node\ (
    echo ERROR: Failed to rename "%NodeName%" to "node" after %RenameAttempts% attempts.
    popd
    exit /b 1
  )
)

@Rem Print node version
echo Node version: & node\node.exe -v

@Rem Pop working directory
popd