@echo off
setlocal EnableExtensions

rem Requires Administrator.
rem Maps syncservice.groovestats.com -> IP of syncplay.letalex.dev

set "ALIAS=syncservice.groovestats.com"
set "TARGET=syncplay.letalex.dev"
set "MARKER=# itgmania-custom-sync"
set "HOSTS=%SystemRoot%\System32\drivers\etc\hosts"

net session >nul 2>&1
if errorlevel 1 (
  echo Run this script as Administrator.
  pause
  exit /b 1
)

for /f "tokens=1" %%I in ('powershell -NoProfile -Command "(Resolve-DnsName -Name '%TARGET%' -Type A | Select-Object -First 1).IPAddress"') do set "IP=%%I"
if not defined IP (
  echo Failed to resolve %TARGET%
  pause
  exit /b 1
)

powershell -NoProfile -Command ^
  "$p='%HOSTS%'; $alias='%ALIAS%'; $marker='%MARKER%'; $ip='%IP%';" ^
  "$lines = Get-Content -LiteralPath $p -ErrorAction Stop;" ^
  "$kept = $lines | Where-Object { $_ -notmatch [regex]::Escape($alias) -and $_ -notmatch [regex]::Escape($marker) };" ^
  "$kept + ('{0}  {1}  {2}' -f $ip, $alias, $marker) | Set-Content -LiteralPath $p -Encoding ascii"
if errorlevel 1 (
  echo Failed to update hosts file.
  pause
  exit /b 1
)

ipconfig /flushdns >nul
echo Enabled: %ALIAS% -> %IP% (%TARGET%)
echo.
echo Checking...

findstr /C:"%ALIAS%" "%HOSTS%" | findstr /C:"%IP%" >nul
if errorlevel 1 (
  echo FAIL: hosts file does not contain expected entry.
  pause
  exit /b 1
)
echo OK: hosts entry present:
findstr /C:"%ALIAS%" "%HOSTS%"

for /f "tokens=1" %%R in ('powershell -NoProfile -Command "(Resolve-DnsName -Name '%ALIAS%' -Type A | Select-Object -First 1).IPAddress"') do set "RESOLVED=%%R"
if /I "%RESOLVED%"=="%IP%" (
  echo OK: %ALIAS% resolves to %RESOLVED%
) else (
  echo FAIL: %ALIAS% resolves to "%RESOLVED%" expected "%IP%"
  pause
  exit /b 1
)

echo.
pause
endlocal
