#Requires -RunAsAdministrator
# Attaches the IceBreaker FPGA (FTDI FT2232H, VID 0403) to WSL2 via usbipd-win.
# Run this on the Windows host before opening the devcontainer.

$ErrorActionPreference = 'Stop'

if (-not (Get-Command usbipd -ErrorAction SilentlyContinue)) {
    Write-Error "usbipd not found. Install it from: https://github.com/dorssel/usbipd-win/releases"
    exit 1
}

# Find all devices with FTDI VID 0403
$devices = usbipd list | Where-Object { $_ -match '0403' }

if (-not $devices) {
    Write-Error "No FTDI device (VID 0403) found. Is the IceBreaker plugged in?"
    exit 1
}

if (($devices | Measure-Object).Count -gt 1) {
    Write-Host "Multiple FTDI devices found:"
    $devices | ForEach-Object { Write-Host "  $_" }
    Write-Error "Ambiguous. Unplug other FTDI devices or run 'usbipd attach --wsl --busid <BUSID>' manually."
    exit 1
}

# Extract BUSID (first token on the line, e.g. "3-1")
$busid = ($devices -split '\s+')[0].Trim()

Write-Host "Attaching IceBreaker at bus ID $busid to WSL2..."
usbipd attach --wsl --busid $busid
Write-Host "Done. You can now open the devcontainer and use iceprog."
