param([string]$Port, [string]$EnvFile)
while ($true) {
    $log = [System.IO.Path]::GetTempFileName()
    $proc = Start-Process -FilePath '.\cloudflared.exe' `
        -ArgumentList "tunnel --url http://localhost:$Port --no-autoupdate" `
        -RedirectStandardError $log -PassThru -NoNewWindow
    $url = $null
    for ($i = 0; $i -lt 60; $i++) {
        Start-Sleep -Seconds 1
        $txt = try { Get-Content $log -Raw -ErrorAction Stop } catch { '' }
        if ($txt -match 'https://[a-z0-9-]+\.trycloudflare\.com') {
            $url = $Matches[0]; break
        }
    }
    if ($url) {
        $e = Get-Content $EnvFile -Raw
        $e = $e -replace '(?m)^EXTERNAL_URL=.*', "EXTERNAL_URL=$url"
        $e = $e -replace '(?m)^# EXTERNAL_URL=.*', "EXTERNAL_URL=$url"
        Set-Content $EnvFile $e -NoNewline
        Write-Host "Remote access URL: $url"
        $lines = $e -split '
?
'
        $mu = ($lines | Where-Object { $_ -match '^MAILBOX_URL=' }) -replace '^MAILBOX_URL=',''
        $ms = ($lines | Where-Object { $_ -match '^MAILBOX_SECRET=' }) -replace '^MAILBOX_SECRET=',''
        $su = ($lines | Where-Object { $_ -match '^SERVER_UUID=' }) -replace '^SERVER_UUID=',''
        if ($mu -and $ms -and $su) {
            $body = ConvertTo-Json @{ uuid=$su; url=$url; secret=$ms }
            try { Invoke-RestMethod -Uri "$mu/api/register" -Method Post -Body $body -ContentType 'application/json' } catch {}
        }
    } else {
        Write-Host 'Warning: Tunnel URL not detected -- remote access unavailable this session.'
    }
    $proc | Wait-Process -ErrorAction SilentlyContinue
    Remove-Item $log -ErrorAction SilentlyContinue
    Write-Host 'Tunnel exited -- restarting in 10s...'
    Start-Sleep -Seconds 10
}
