#!/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..."
\$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

\$gpu_driver = "$driver.exe"

\$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-Sleep 30

trap {
    Write-Error "An unexpected error occurred: \$_"
    continue
}

try {
    \$process = Start-Process -FilePath \$download_dest_path -ArgumentList '/s /noreboot' -PassThru
    \$process.ProcessorAffinity = 0x3
    \$process.WaitForExit(1200 * 1000)

    if (\$process.HasExited) {
        Write-Host "Process exited normally."
    } else {
        Write-Host "Process did not exit within the timeout period. Stopping the process."
        \$process.Kill()
    }
} catch {
    Write-Error "error"
    continue
}


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

while ((Get-Date) -lt (\$start_time.AddMinutes(10))) {
        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="windows2019std-gpu-$driver.ps1"
    script_filename=$(echo $script_file | tr '[:upper:]' '[:lower:]')
    echo "$script_content" > "$script_filename"
    echo "Created $script_filename"
done
