@echo off
setlocal EnableExtensions
chcp 65001 >nul

set "NOWDNS_URL=%~1"
if defined NOWDNS_URL goto :open

set "NOWDNS_ROOT=%~dp0"
if not exist "%NOWDNS_ROOT%nowdns.exe" if exist "%NOWDNS_ROOT%..\bin\" for %%I in ("%NOWDNS_ROOT%..") do set "NOWDNS_ROOT=%%~fI\"
set "NOWDNS_CONFIG=%NOWDNS_ROOT%config.yaml"
set "NOWDNS_LISTEN=127.0.0.1:8080"
if exist "%NOWDNS_CONFIG%" (
    for /f "tokens=1,* delims=:" %%A in ('findstr /R /C:"^[ ]*listen:[ ]*" "%NOWDNS_CONFIG%"') do (
        set "NOWDNS_LISTEN=%%B"
        goto :listenFound
    )
)

:listenFound
for /f "tokens=1 delims=#" %%A in ("%NOWDNS_LISTEN%") do set "NOWDNS_LISTEN=%%A"
set "NOWDNS_LISTEN=%NOWDNS_LISTEN: =%"
set "NOWDNS_LISTEN=%NOWDNS_LISTEN:"=%"

if /i "%NOWDNS_LISTEN:~0,8%"=="0.0.0.0:" set "NOWDNS_URL=http://127.0.0.1%NOWDNS_LISTEN:~7%"
if /i "%NOWDNS_LISTEN:~0,5%"=="[::]:" set "NOWDNS_URL=http://127.0.0.1:%NOWDNS_LISTEN:~5%"
if /i "%NOWDNS_LISTEN:~0,2%"=="*:" set "NOWDNS_URL=http://127.0.0.1%NOWDNS_LISTEN:~1%"
if /i "%NOWDNS_LISTEN:~0,4%"=="any:" set "NOWDNS_URL=http://127.0.0.1%NOWDNS_LISTEN:~3%"
if "%NOWDNS_LISTEN:~0,1%"==":" set "NOWDNS_URL=http://127.0.0.1%NOWDNS_LISTEN%"
if not defined NOWDNS_URL set "NOWDNS_URL=http://%NOWDNS_LISTEN%"

:open
start "" "%NOWDNS_URL%"
set "EXIT_CODE=%ERRORLEVEL%"
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0service.ps1" -Action message -MessageAction open-ui -MessageExitCode %EXIT_CODE% -MessageURL "%NOWDNS_URL%"
pause >nul
exit /b %EXIT_CODE%
