@echo off
setlocal
cd /d "%~dp0"

set "UPDATE_URL=https://atlas-games.fun/downloads/latest.json"

if not exist "duskbound.version" (
    echo duskbound.version is missing.
    pause
    exit /b 1
)
set /p CURRENT_VERSION=<"duskbound.version"

powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$ErrorActionPreference = 'Stop';" ^
  "try {" ^
  "  $manifest = Invoke-RestMethod -Uri $env:UPDATE_URL -TimeoutSec 5;" ^
  "  if ([version]$manifest.windows_version -gt [version]$env:CURRENT_VERSION) {" ^
  "    Write-Host ('Duskbound ' + $manifest.windows_version + ' is available. Updating...');" ^
  "    $zip = Join-Path $env:TEMP 'duskbound-update.zip';" ^
  "    $stage = Join-Path $env:TEMP 'duskbound-update';" ^
  "    Invoke-WebRequest -Uri $manifest.windows_url -OutFile $zip -TimeoutSec 60;" ^
  "    $actual = (Get-FileHash -Algorithm SHA256 -LiteralPath $zip).Hash.ToLowerInvariant();" ^
  "    if ($actual -ne $manifest.windows_sha256) { throw 'Update integrity check failed.' }" ^
  "    Remove-Item $stage -Recurse -Force -ErrorAction SilentlyContinue;" ^
  "    Expand-Archive -LiteralPath $zip -DestinationPath $stage -Force;" ^
  "    Get-ChildItem (Join-Path $stage 'duskbound-windows') | Where-Object Name -ne 'run-duskbound.bat' | Copy-Item -Destination . -Recurse -Force;" ^
  "    Remove-Item $zip, $stage -Recurse -Force -ErrorAction SilentlyContinue;" ^
  "  }" ^
  "} catch { Write-Warning ($_.Exception.Message + ' Starting the current version.') }"

if not exist "Atlas.dll.sha256" (
    echo Atlas.dll.sha256 is missing.
    pause
    exit /b 1
)

set /p EXPECTED_HASH=<"Atlas.dll.sha256"
for /f %%H in ('powershell -NoProfile -Command "(Get-FileHash -Algorithm SHA256 -LiteralPath 'Atlas.dll').Hash.ToLowerInvariant()"') do set ACTUAL_HASH=%%H

if /i not "%EXPECTED_HASH%"=="%ACTUAL_HASH%" (
    echo Atlas.dll integrity check failed.
    echo The engine library is damaged or has been replaced.
    pause
    exit /b 1
)

start "" /wait "duskbound.exe"
