# ectool test script - run as Administrator
# Tests EC communication, temperature, fan, battery and saves result to .txt
# Use cmd to capture stderr as text (no PowerShell error wrapper)

$EctoolPath = "C:\Program Files\crosec\ectool.exe"
$ReportDir = $PSScriptRoot
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$ReportFile = Join-Path $ReportDir "ectool_test_$Timestamp.txt"

$Report = ""

function Run-Ectool {
    param([string]$Cmd, [string]$Desc)
    $script:Report += "`n--- $Desc ---`n"
    if (-not (Test-Path $EctoolPath)) {
        $script:Report += "ectool not found at: $EctoolPath`n"
        return
    }
    try {
        $argList = $Cmd -split "\s+", 0, "IgnoreCase"
        $argStr = ($argList | ForEach-Object { $_ }) -join " "
        $cmdLine = "`"$EctoolPath`" $argStr 2>&1"
        $out = cmd /c $cmdLine
        $script:Report += ($out | Out-String)
    } catch {
        $script:Report += "Error: $($_.Exception.Message)`n"
    }
}

$Report += "ectool test report`n"
$Report += "Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')`n"
$Report += "Computer: $env:COMPUTERNAME`n"

# 1. Basic EC communication
Run-Ectool "hello" "1. EC communication (hello)"
Run-Ectool "version" "2. EC version"

# 2. Temperature (try common sensor IDs)
Run-Ectool "temps 0" "3. Temperature sensor 0"
Run-Ectool "temps 1" "4. Temperature sensor 1"
Run-Ectool "tempsinfo 0" "5. Temperature sensor 0 info"

# 3. Fan
Run-Ectool "pwmgetnumfans" "6. Number of fans"
Run-Ectool "pwmgetfanrpm all" "7. Fan RPM (all)"

# 4. Power / battery
Run-Ectool "battery" "8. Battery info"
Run-Ectool "powerinfo" "9. Power info"

# 5. System
Run-Ectool "sysinfo" "10. System info"
Run-Ectool "chipinfo" "11. Chip info"

# 6. Optional: thermal thresholds (may not be supported on all boards)
Run-Ectool "thermalget" "12. Thermal thresholds (thermalget)"

# Summary
$Report += "`n--- Summary ---`n"
if ($Report -match "ioctl errno 6|EC result 255") {
    $Report += "This report contains 'ioctl errno 6' or 'EC result 255'.`n"
    $Report += "If you DO have Chrome EC bus: often driver/interface or permission.`n"
    $Report += "  - Run PowerShell as Administrator.`n"
    $Report += "  - Check crosec service is running (services.msc).`n"
    $Report += "  - Try: ectool --interface=dev hello  or  ectool --name=cros_ec hello`n"
    $Report += "If no Chrome EC hardware, use HWiNFO or Core Temp for temperature.`n"
} else {
    $Report += "Some commands succeeded. Chrome EC communication is working.`n"
}

$Report | Set-Content -Path $ReportFile -Encoding UTF8
Write-Host "Report saved: $ReportFile" -ForegroundColor Green
Write-Host $Report
