@echo off
title Webserver for %CD%

REM Ensure python is installed
set LocalPythonEmbeddedDir=%LOCALAPPDATA%\python-3.11.4-embed-amd64
if not exist "%LocalPythonEmbeddedDir%\python.exe" (
echo Installing python
curl -L -o "%TEMP%\python-3.11.4-embed-amd64.zip" "https://www.python.org/ftp/python/3.11.4/python-3.11.4-embed-amd64.zip"
md "%LocalPythonEmbeddedDir%"
tar -x -f "%TEMP%\python-3.11.4-embed-amd64.zip" -C "%LocalPythonEmbeddedDir%"
)

REM Find a free dynamic port to start our server on
echo Finding free port to start webserver on
set freePort=
set startPort=49152
:SEARCHPORT
netstat -o -n -a | find "LISTENING" | find ":%startPort% " > NUL
if "%ERRORLEVEL%" equ "0" (
  set /a startPort +=1
  GOTO :SEARCHPORT
) ELSE (
  set freePort=%startPort%
  GOTO :FOUNDPORT
)
:FOUNDPORT
echo Port available - %startPort%
set PortNo=%freePort%

echo Starting local webserver at http://localhost:%PortNo%
echo Close this window when you are done with the content to terminate the server
start "" /b "%LocalPythonEmbeddedDir%\python.exe" ServerCustomPort.py %PortNo%
timeout /T 1 /nobreak>nul
start /wait "" "http://localhost:%PortNo%/"
