#!/bin/bash

gpu_drivers=(
    "A100" "A4000" "A40" "A5000" "A6000" "GT710" "GT730" "GTX1650"
    "GTX1660" "K40" "K620" "K80" "P1000" "P600" "P620" "RTX2060"
    "RTX3060TI" "RTX4060" "RTX4090" "RTXA4000" "RTXA5000" "RTXA6000"
    "T1000" "V100" "P100"
)

for driver in "${gpu_drivers[@]}"; do
    script_content=$(cat <<EOF
Write-Output "Installing NVIDIA GPU driver $driver..."

\$gpu_driver = "$driver.exe"
\$driver_path = "C:\Users\Administrator\Downloads\PRO\APPS\SETUP\SETUPBD\Winx64\SetupBD.exe"

function Check-InternetConnection {
    try {
        \$tcpClient = New-Object System.Net.Sockets.TcpClient
        \$tcpClient.Connect("www.google.com", 80)
        \$tcpClient.Close()
        return \$true
    }
    catch {
        return \$false
    }
}

function Wait-ForInternetConnection {
    \$timeout_minutes = 3
    \$start_time = Get-Date
    while (\$true) {
        if (Check-InternetConnection) {
            Write-Output("Connected to the network!")
            break
        }
        elseif ((Get-Date) - \$start_time -ge (New-TimeSpan -Minutes \$timeout_minutes)) {
            Write-Output("After \$timeout_minutes minutes of waiting, the network is still not connected! Install driver")
            \$driver_install_info = Start-Process -FilePath \$driver_path -ArgumentList "/s" -NoNewWindow -Wait
            break
        }
        else {
            Write-Output("Waiting for the network connection...")
            Start-Sleep -Seconds 5
        }
    }
}

Wait-ForInternetConnection

\$gpu_driver_download_url = "https://download.cloudclusters.io/\$gpu_driver"
Write-Output("gpu_driver_download_url is: \$gpu_driver_download_url")

\$download_dest_path = "C:\Users\Administrator\Downloads\nvidia.exe"
Invoke-WebRequest -Uri \$gpu_driver_download_url -OutFile \$download_dest_path


Start-Process -FilePath \$download_dest_path -ArgumentList '/s /noreboot' -Wait

\$install_successful = \$false
\$start_time = Get-Date

while ((Get-Date) -lt (\$start_time.AddMinutes(30))) {
        try {
            & nvidia-smi.exe
            \$install_successful = \$true
            break
        } catch {
            Write-Output "wait"
            Start-Sleep -Seconds 60
        }
    }

if (-not \$install_successful) {
    Write-Host "Driver installation failed within the 30-minute timeout."
    return
} else {
    Write-Host "Driver installed successfully."
}

Write-Output "install-finished"
EOF
)

    script_file="windows10-gpu-$driver.ps1"
    script_filename=$(echo $script_file | tr '[:upper:]' '[:lower:]')
    echo "$script_content" > "$script_filename"
    echo "Created $script_filename"
done
