@echo off
setlocal

cd /d "%~dp0"

if not exist ".env" (
  echo No .env found. Using built-in defaults and any current environment variables.
)

if not exist "data" (
  mkdir "data"
)

if defined MAINTAINARR_ADDR (
  set "BIND_ADDR=%MAINTAINARR_ADDR%"
) else (
  for /f "usebackq delims=" %%P in (`powershell -NoProfile -Command ^
    "$listener = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue; " ^
    "foreach ($port in 8080..8090) { if (-not ($listener | Where-Object LocalPort -eq $port)) { Write-Output $port; break } }"`) do (
    set "PORT=%%P"
  )

  if not defined PORT (
    echo No free port found in the range 8080-8090.
    echo Set MAINTAINARR_ADDR manually and try again.
    exit /b 1
  )

  set "BIND_ADDR=:%PORT%"
  set "MAINTAINARR_ADDR=%BIND_ADDR%"
)

echo Starting Maintainarr on http://localhost%MAINTAINARR_ADDR%
go run ./cmd/maintainarr

endlocal
