@echo off
setlocal enabledelayedexpansion

where cloudflared >nul 2>nul
if %errorlevel%==0 (
    echo cloudflared is already installed.
) else (
    echo cloudflared is not installed. Installing...
    winget install --id Cloudflare.cloudflared -e --source winget
    if %errorlevel% neq 0 (
        echo Failed to install cloudflared
        exit /b
    )
    echo cloudflared installed. reopening
    timeout /t 3 /nobreak >nul
    exit /b
)


set "RANDOM_SUBDOMAIN="
for /l %%i in (1,1,6) do (
    set /a "rand=!random! %% 36"
    for %%a in (a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9) do (
        if !rand! equ %%i set "RANDOM_SUBDOMAIN=!RANDOM_SUBDOMAIN!%%a"
    )
)


echo Running: cloudflared tunnel --url http://localhost --hostname !RANDOM_SUBDOMAIN!.trycloudflare.com


for /f "skip=3 delims=" %%i in ('cloudflared tunnel --url http://localhost --hostname !RANDOM_SUBDOMAIN!.trycloudflare.com') do (
    set "output=%%i"
    if defined output (
        echo Cloudflare output: !output!
        :: Check if the line contains "https://"
        echo !output! | findstr /b "https://" >nul
        if %errorlevel%==0 (
            echo Found URL: !output!
            start !output!
            exit /b
        )
    )
)

:: End of script
endlocal
