param([switch]$Elevated)

$ErrorActionPreference = 'Stop'
$scriptPath = $MyInvocation.MyCommand.Path
$kitRoot = Split-Path -Parent $scriptPath
$infPath = Join-Path $kitRoot 'Driver\android_winusb.inf'

function Test-Administrator {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

if (-not (Test-Administrator)) {
    Write-Host 'Administrator permission is required. Confirm the Windows UAC prompt.' -ForegroundColor Yellow
    $arguments = @(
        '-NoProfile',
        '-ExecutionPolicy', 'Bypass',
        '-File', ('"{0}"' -f $scriptPath),
        '-Elevated'
    )
    $process = Start-Process -FilePath 'powershell.exe' -ArgumentList $arguments -Verb RunAs -Wait -PassThru
    exit $process.ExitCode
}

if (-not (Test-Path -LiteralPath $infPath)) {
    Write-Host "ERROR: driver INF is missing: $infPath" -ForegroundColor Red
    exit 2
}

Write-Host 'TECHNOZON X11 - Android Bootloader Interface driver' -ForegroundColor Cyan
Write-Host "Driver: $infPath"
Write-Host 'Adding the signed driver package to Windows Driver Store...' -ForegroundColor Yellow

$output = & pnputil.exe /add-driver $infPath /install 2>&1
$exitCode = $LASTEXITCODE

$bootloader = Get-PnpDevice -PresentOnly -ErrorAction SilentlyContinue | Where-Object {
    $_.FriendlyName -match 'Android Bootloader Interface|Android.*Fastboot' -or
    $_.InstanceId -match '^USB\\VID_18D1&PID_4E40'
} | Select-Object -First 1

$driverStoreOutput = & pnputil.exe /enum-drivers 2>&1
$driverInStore = ((@($driverStoreOutput) -join "`n") -match '(?i)android_winusb\.inf')

if ($exitCode -ne 0 -and -not $driverInStore -and -not $bootloader) {
    $output | ForEach-Object { Write-Host $_ }
    Write-Host "ERROR: pnputil failed with exit code $exitCode and the driver was not found in Driver Store." -ForegroundColor Red
    exit $exitCode
}

if ($exitCode -ne 0) {
    Write-Host "pnputil returned exit code $exitCode, but readback confirms that the driver is installed." -ForegroundColor Yellow
} else {
    Write-Host 'Driver package installation completed.' -ForegroundColor Green
}

if ($bootloader) {
    Write-Host "PASS: $($bootloader.FriendlyName) is detected and ready." -ForegroundColor Green
} else {
    Write-Host 'PASS: driver package is installed in Windows Driver Store.' -ForegroundColor Green
    Write-Host 'The interface will appear after the X11 enters fastboot mode.' -ForegroundColor Yellow
}

exit 0
