@echo off
setlocal

set "SCRIPT_DIR=%~dp0"
for %%I in ("%SCRIPT_DIR%..") do set "APP_HOME=%%~fI"
set "CONFIG_FILE=%APP_HOME%\conf\castara.conf"

if exist "%CONFIG_FILE%" (
    for /f "usebackq eol=# tokens=1* delims==" %%A in ("%CONFIG_FILE%") do (
        if not "%%~A"=="" set "%%~A=%%~B"
    )
)

if not defined MEDIA_SERVER_PORT set "MEDIA_SERVER_PORT=8181"
if not defined MEDIA_SERVER_BROWSER_HOST set "MEDIA_SERVER_BROWSER_HOST=127.0.0.1"
if not defined MEDIA_SERVER_OPEN_BROWSER set "MEDIA_SERVER_OPEN_BROWSER=true"
if not defined JAVA_EXE (
    if defined JAVA_HOME (
        set "JAVA_EXE=%JAVA_HOME%\bin\javaw.exe"
    ) else (
        set "JAVA_EXE=javaw.exe"
    )
)

if not exist "%APP_HOME%\run" mkdir "%APP_HOME%\run"

powershell -NoProfile -ExecutionPolicy Bypass -Command "$appHome = $env:APP_HOME; $argumentList = @('-Dmedia.server.port=' + $env:MEDIA_SERVER_PORT, '-Dmedia.server.browserHost=' + $env:MEDIA_SERVER_BROWSER_HOST, '-Dmedia.server.openBrowser=' + $env:MEDIA_SERVER_OPEN_BROWSER); if ($env:MEDIA_SERVER_BIND_HOST) { $argumentList += '-Dmedia.server.bindHost=' + $env:MEDIA_SERVER_BIND_HOST }; if ($env:MEDIA_SERVER_ADVERTISED_HOST) { $argumentList += '-Dmedia.server.advertisedHost=' + $env:MEDIA_SERVER_ADVERTISED_HOST }; $argumentList += '-cp'; $argumentList += (Join-Path $appHome 'lib\*'); $argumentList += 'com.maa.mediaserver.server.MainKt'; $process = Start-Process -FilePath $env:JAVA_EXE -ArgumentList $argumentList -WorkingDirectory $appHome -PassThru; Set-Content -Path (Join-Path $appHome 'run\server.pid') -Value $process.Id"

echo Castara started.
echo Browser: http://%MEDIA_SERVER_BROWSER_HOST%:%MEDIA_SERVER_PORT%/
endlocal