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

set AD_GUI_HOST=0.0.0.0
set AD_GUI_PORT=8765
if not defined AD_GUI_USER set "AD_GUI_USER=ad"

if not defined AD_GUI_PASSWORD (
  echo Login user: %AD_GUI_USER%
  for /f "usebackq delims=" %%P in (`powershell -NoProfile -Command "$p = Read-Host 'Set AD GUI password' -AsSecureString; $b = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($p); try { [Runtime.InteropServices.Marshal]::PtrToStringBSTR($b) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($b) }"`) do set "AD_GUI_PASSWORD=%%P"
)

if not defined AD_GUI_PASSWORD (
  echo.
  echo Password is required for remote access.
  pause
  exit /b 1
)

echo Starting AD GUI remote server...
echo.
echo Login user:
echo   %AD_GUI_USER%
echo.
echo Local computer URLs:
for /f "tokens=2 delims=:" %%A in ('ipconfig ^| findstr /R /C:"IPv4"') do (
  for /f "tokens=* delims= " %%B in ("%%A") do echo   http://%%B:%AD_GUI_PORT%/
)
echo.
echo Remote users must be on the same LAN/VPN and open one of the URLs above.
echo Press Ctrl+C to stop the server.
echo.

python -B "%~dp0ad_gui.py" --host %AD_GUI_HOST% --port %AD_GUI_PORT% --no-open --auth-user "%AD_GUI_USER%"
if errorlevel 1 (
  echo.
  echo AD GUI remote server failed.
  echo If pyserial is missing, run:
  echo python -m pip install -r "%~dp0requirements-ad-terminal.txt"
  echo.
  echo If remote browser cannot connect, allow TCP port %AD_GUI_PORT% in Windows Firewall.
  echo See:
  echo "%~dp0README_AD_REMOTE_GUI.md"
  echo.
  pause
)
