' ============================================
' Fix IIS SSL - ANSTECHNOLOGY (Auto-Elevate)
' ============================================
' Script นี้จะติดตั้ง SSL Certificate ให้กับเว็บไซต์
' Double-click แล้ว Accept UAC prompt เพื่อติดตั้ง
' ============================================

Option Explicit

' Check if running as admin
Dim IsAdmin
IsAdmin = False
On Error Resume Next
IsAdmin = CreateObject("WScript.Shell").Run("net session > nul 2>&1", 0, True) = 0
On Error GoTo 0

If Not IsAdmin Then
    ' Restart script with admin privileges (auto-elevate)
    Dim Shell
    Set Shell = CreateObject("Shell.Application")
    Shell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """", "", "runas", 5
    WScript.Quit
End If

' ============================================
' Running as Admin from here
' ============================================
Dim WshShell, FSO, ScriptDir, PfxPath, PfxPass, Thumbprint, AppId, RetCode, TempFile, ImportLog
Set WshShell = CreateObject("WScript.Shell")
Set FSO = CreateObject("Scripting.FileSystemObject")

' Configuration
ScriptDir = FSO.GetParentFolderName(WScript.ScriptFullName) & "\"
PfxPath = ScriptDir & "ssl_temp\server.pfx"
PfxPass = "Anstech@2024!"
AppId = "{4dc3e181-e14b-4a21-b022-59fc669b0914}"
TempFile = WshShell.ExpandEnvironmentStrings("%TEMP%") & "\cert_thumbprint.txt"
ImportLog = ScriptDir & "ssl_temp\import.log"

' Show initial message
WshShell.PopUp "📦 กำลังติดตั้ง SSL Certificate สำหรับ ans-technology.la..." & vbCrLf & vbCrLf & "กรุณารอสักครู่...", 2, "SSL Setup", 64

' Step 1: Delete old certs
WshShell.Run "powershell -Command ""Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.DnsNameList -like '*ans-technology.la*' -or $_.FriendlyName -like '*ANSTECHNOLOGY*' } | Remove-Item -Force""", 0, True

' Step 2: Import PFX certificate
If FSO.FileExists(PfxPath) Then
    WshShell.Run "certutil -f -p " & PfxPass & " -importpfx """ & PfxPath & """ > """ & ImportLog & """ 2>&1", 0, True
Else
    ' If PFX doesn't exist, create a new certificate
    WshShell.PopUp "⚠️ ไม่พบไฟล์ PFX จะสร้าง Certificate ใหม่...", 1, "SSL Setup", 48
    WshShell.Run "powershell -Command ""New-SelfSignedCertificate -DnsName 'ans-technology.la','103.114.146.251','localhost' -CertStoreLocation 'Cert:\LocalMachine\My' -FriendlyName 'ANSTECHNOLOGY IIS' -NotAfter (Get-Date).AddYears(5) | Out-Null""", 0, True
End If

' Step 3: Get thumbprint
WshShell.Run "powershell -Command ""(Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.DnsNameList -like '*ans-technology.la*' } | Select-Object -First 1).Thumbprint | Out-File -FilePath '" & TempFile & "' -Encoding ASCII""", 0, True
WScript.Sleep 2000

' Read thumbprint from file
Dim File, ThumbprintText
If FSO.FileExists(TempFile) Then
    Set File = FSO.OpenTextFile(TempFile, 1)
    ThumbprintText = Trim(File.ReadLine())
    File.Close
End If

If ThumbprintText = "" Then
    WshShell.PopUp "❌ ไม่พบ Certificate! การติดตั้งล้มเหลว", 3, "SSL Error", 16
    WScript.Quit
End If

' Step 4: Delete old SSL bindings
WshShell.Run "netsh http delete sslcert ipport=0.0.0.0:443", 0, True
WshShell.Run "netsh http delete sslcert hostnameport=ans-technology.la:443", 0, True

' Step 5: Add new SSL binding
Dim BindCmd
BindCmd = "netsh http add sslcert hostnameport=ans-technology.la:443 certhash=" & ThumbprintText & " appid=" & AppId
WshShell.Run BindCmd, 0, True

' Step 6: Restart IIS
WshShell.Run "iisreset /restart", 0, True

' Success message
WshShell.PopUp "✅ ติดตั้ง SSL เสร็จสมบูรณ์!" & vbCrLf & vbCrLf & _
    "เว็บไซต์ของคุณพร้อมใช้งานผ่าน HTTPS แล้ว:" & vbCrLf & _
    "https://ans-technology.la/" & vbCrLf & vbCrLf & _
    "⚠️ ใบรับรองเป็นแบบ Self-signed" & vbCrLf & _
    "   จะขึ้นคำเตือนในเบราว์เซอร์" & vbCrLf & _
    "   ให้คลิก Advanced → Proceed", 10, "SSL Success", 64

' Clean up temp file
If FSO.FileExists(TempFile) Then FSO.DeleteFile TempFile
If FSO.FileExists(TempFile) Then
    Dim FileStream
    Set FileStream = FSO.OpenTextFile(TempFile, 1)
    Thumbprint = Trim(FileStream.ReadLine())
    FileStream.Close
    FSO.DeleteFile TempFile
End If

If Thumbprint = "" Then
    WshShell.PopUp "Failed to create SSL certificate!" & vbCrLf & vbCrLf & "Please run the batch file manually as Administrator:", 0, "SSL Error", 16
    WshShell.PopUp "C:\AppServ\www\anstechnology\fix_ssl_iis.bat", 0, "Manual Steps", 64
    WScript.Quit 1
End If

' Step 4: Remove old SSL binding
WshShell.Run "netsh http delete sslcert ipport=0.0.0.0:443", 0, True

' Step 5: Add new SSL binding
RetCode = WshShell.Run("netsh http add sslcert ipport=0.0.0.0:443 certhash=" & Thumbprint & " appid={4dc3e181-e14b-4a21-b022-59fc669b0914}", 0, True)

' Step 6: Restart IIS
WshShell.Run "iisreset /restart", 1, True

' Done!
WshShell.PopUp "SSL Setup Complete!" & vbCrLf & vbCrLf & _
    "Certificate Thumbprint: " & Thumbprint & vbCrLf & vbCrLf & _
    "https://ans-technology.la/  is now ready" & vbCrLf & vbCrLf & _
    "Note: Self-signed cert shows a browser warning.", 0, "SSL Setup - Success", 64
