' Test harness for the watchdog's UrlOk detection logic.
' Runs the SAME function against a working URL and a bogus URL, so we can prove
' the dead-tunnel detection actually fires instead of silently always returning True.
' This file is intentionally ASCII-only.
Option Explicit

Dim fso, urlFile, publicUrl
Set fso = CreateObject("Scripting.FileSystemObject")
urlFile = "C:\FundamentalWorkbench\deploy\public_url.txt"

Dim ts
Set ts = fso.OpenTextFile(urlFile, 1, False)
Dim raw
If Not ts.AtEndOfStream Then raw = ts.ReadAll
ts.Close

WScript.Echo "raw file content    : [" & raw & "]"
WScript.Echo "after CleanUrl      : [" & CleanUrl(raw) & "]"
publicUrl = CleanUrl(raw)

WScript.Echo "recorded public url : " & publicUrl
WScript.Echo "LOCAL  probe -> " & UrlOk("http://127.0.0.1:8765/reports/dashboard/version.json")
WScript.Echo "PUBLIC probe -> " & UrlOk(publicUrl & "/reports/dashboard/version.json")
WScript.Echo "BOGUS  probe -> " & UrlOk("https://definitely-not-a-real-tunnel-xyz.trycloudflare.com/reports/dashboard/version.json")
WScript.Echo "DEAD   probe -> " & UrlOk("https://shadow-beneficial-rca-smallest.trycloudflare.com/reports/dashboard/version.json")

' Normalise a URL read from disk (identical to the watchdog's copy).
Function CleanUrl(s)
    Dim p, i, c, e
    CleanUrl = ""
    p = InStr(s, "http")
    If p = 0 Then Exit Function
    s = Mid(s, p)
    e = Len(s)
    For i = 1 To Len(s)
        c = AscW(Mid(s, i, 1))
        If c <= 32 Then
            e = i - 1
            Exit For
        End If
    Next
    CleanUrl = Left(s, e)
End Function

' True when the URL answers with HTTP 200 (short timeouts, no proxy).
Function UrlOk(url)
    Dim http, code
    UrlOk = False
    On Error Resume Next
    Set http = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    If Err.Number <> 0 Then
        Set http = CreateObject("MSXML2.ServerXMLHTTP")
    End If
    If Err.Number <> 0 Then Exit Function
    http.setTimeouts 8000, 8000, 8000, 12000
    http.Open "GET", url, False
    http.setRequestHeader "Cache-Control", "no-store"
    http.Send
    code = http.Status
    If code = 200 Then UrlOk = True
    On Error GoTo 0
End Function
