@echo off
setlocal EnableExtensions
title Update Luuma Player

set "DOWNLOAD_URL=%~1"
if "%DOWNLOAD_URL%"=="" set "DOWNLOAD_URL=https://luuma.cloud/downloads/player/luuma-player-windows-x32.zip"

set "INSTALL_DIR=%~dp0"
set "TEMP_ROOT=%TEMP%\LuumaPlayerUpdate_%RANDOM%%RANDOM%"
set "ZIP_PATH=%TEMP_ROOT%\luuma-player-windows-x32.zip"
set "EXTRACT_DIR=%TEMP_ROOT%\extract"

echo Luuma Player update
echo.
echo Install folder: %INSTALL_DIR%
echo Download: %DOWNLOAD_URL%
echo.

mkdir "%TEMP_ROOT%" >nul 2>&1
if errorlevel 1 (
  echo Could not create temporary folder.
  pause
  exit /b 1
)

echo Downloading latest player...
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '%DOWNLOAD_URL%' -OutFile '%ZIP_PATH%'"
if errorlevel 1 (
  echo Download failed.
  rmdir /s /q "%TEMP_ROOT%" >nul 2>&1
  pause
  exit /b 1
)

echo Extracting update...
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; Expand-Archive -LiteralPath '%ZIP_PATH%' -DestinationPath '%EXTRACT_DIR%' -Force"
if errorlevel 1 (
  echo Extract failed.
  rmdir /s /q "%TEMP_ROOT%" >nul 2>&1
  pause
  exit /b 1
)

set "SOURCE_DIR=%EXTRACT_DIR%"
if exist "%EXTRACT_DIR%\luuma-player-windows-x32.exe" set "SOURCE_DIR=%EXTRACT_DIR%"
if exist "%EXTRACT_DIR%\luuma-player-ia32.exe" set "SOURCE_DIR=%EXTRACT_DIR%"
for /d %%D in ("%EXTRACT_DIR%\*") do (
  if exist "%%~fD\luuma-player-windows-x32.exe" set "SOURCE_DIR=%%~fD"
  if exist "%%~fD\luuma-player-ia32.exe" set "SOURCE_DIR=%%~fD"
)

if not exist "%SOURCE_DIR%\luuma-player-windows-x32.exe" if not exist "%SOURCE_DIR%\luuma-player-ia32.exe" (
  echo The downloaded ZIP did not contain a Luuma Player executable.
  rmdir /s /q "%TEMP_ROOT%" >nul 2>&1
  pause
  exit /b 1
)

echo Closing Luuma Player if it is running...
taskkill /IM "luuma-player-windows-x32.exe" /F >nul 2>&1
taskkill /IM "luuma-player-ia32.exe" /F >nul 2>&1
taskkill /IM "luuma-player-x64.exe" /F >nul 2>&1
taskkill /IM "Luuma Player.exe" /F >nul 2>&1
timeout /t 2 /nobreak >nul

echo Applying update...
robocopy "%SOURCE_DIR%" "%INSTALL_DIR%" /E /NFL /NDL /NJH /NJS /NP
set "ROBOCOPY_EXIT=%ERRORLEVEL%"
if %ROBOCOPY_EXIT% GEQ 8 (
  echo Update copy failed with code %ROBOCOPY_EXIT%.
  rmdir /s /q "%TEMP_ROOT%" >nul 2>&1
  pause
  exit /b 1
)

rmdir /s /q "%TEMP_ROOT%" >nul 2>&1

echo.
echo Luuma Player updated.
if exist "%INSTALL_DIR%luuma-player-windows-x32.exe" (
  start "" "%INSTALL_DIR%luuma-player-windows-x32.exe"
) else if exist "%INSTALL_DIR%luuma-player-ia32.exe" (
  start "" "%INSTALL_DIR%luuma-player-ia32.exe"
)

exit /b 0
