if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltinRole] "Administrator")) {
		Write-Output "Not elevated: relaunching as admin..."
		Start-Process -FilePath powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
		exit 1
}

if ($env:PROCESSOR_ARCHITEW6432 -eq "AMD64") {
	write-warning "Y'arg Matey, we're off to 64-bit land....."
	if ($myInvocation.Line) {
		&"$env:WINDIR\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile $myInvocation.Line
	}else{
		&"$env:WINDIR\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -file "$($myInvocation.InvocationName)" $args
	}
	exit $LastExitCode
}

$PSProgressPreference = 'SilentlyContinue'

$inf	= '.\OemVista.inf'
$tapExe	= Join-Path $PSScriptRoot 'tapinstall.exe'

$oldLocation = Get-Location
Set-Location -Path $PSScriptRoot

# lista PNP prima dell'install (per poter riconoscere il nuovo device)
$prevPNP = @()
try {
	$prevPNP = Get-CimInstance -ClassName Win32_NetworkAdapter -ErrorAction Stop |
				Where-Object { $_.ServiceName -eq 'tap0901' } |
				ForEach-Object { $_.PNPDeviceID }
} catch { $prevPNP = @() }

# cerca esattamente il device che vogliamo rimuovere (Nome + ServiceName)
$targetPNP = $null
try {
	$targetPNP = Get-CimInstance -ClassName Win32_NetworkAdapter -ErrorAction SilentlyContinue |
				Where-Object { $_.NetConnectionID -eq 'TAP-HT Portal' -and $_.ServiceName -eq 'tap0901' } |
				Select-Object -ExpandProperty PNPDeviceID -ErrorAction SilentlyContinue

	if (-not $targetPNP) {
			# prova 2: Get-PnpDevice (friendly name) -> InstanceId (richiede modulo PnpDevice presente)
			try {
				$p = Get-PnpDevice -FriendlyName 'TAP-HT Portal' -ErrorAction SilentlyContinue |
					Where-Object { $_.Class -ne $null } | Select-Object -ExpandProperty InstanceId -First 1
				if ($p) { $targetPNP = $p }
			} catch {
				# Get-PnpDevice puÃ² non essere disponibile in sistemi molto vecchi; ignoriamo l'errore
			}
	}

	if (-not $targetPNP) {
			# prova 3: usa Get-NetAdapter per ottenere InterfaceDescription e mappalo a Win32_NetworkAdapter
			$net = Get-NetAdapter -Name 'TAP-HT Portal' -ErrorAction SilentlyContinue
			if ($net) {
					$desc = $net.InterfaceDescription
					if ($desc) {
							$targetPNP = Get-CimInstance -ClassName Win32_NetworkAdapter -ErrorAction SilentlyContinue |
										Where-Object { ($_.Description -eq $desc -or $_.Name -eq $desc) -and $_.ServiceName -eq 'tap0901' } |
										Select-Object -ExpandProperty PNPDeviceID -ErrorAction SilentlyContinue
					}
			}
	}
} catch { $targetPNP = $null }

if ($targetPNP) {
	Write-Output "Found existing TAP-HT Portal: $targetPNP"
	$p = Start-Process -FilePath pnputil.exe -ArgumentList '/remove-device', $targetPNP -Wait -PassThru
	if ($p.ExitCode -ne 0) {
		Write-Warning "pnputil returned exit code $($p.ExitCode). Continuing (may require reboot)."
	} else {
		Write-Output "Device removed."
	}
} else {
	Write-Output "No existing TAP-HT Portal found. Proceeding to install."
}

# verifica tapinstall.exe e .inf
if (-not (Test-Path $tapExe)) {
	Write-Error "tapinstall.exe not found at $tapExe"
	exit 2
}
if (-not (Test-Path $inf)) {
	Write-Error "INF not found at $inf"
	exit 2
}

# install (Start-Process con PassThru per leggere ExitCode)
$inst = Start-Process -WindowStyle Hidden -FilePath $tapExe -ArgumentList 'install', $inf, 'tap0901' -Wait -PassThru
if ($inst.ExitCode -ne 0) {
	Write-Error "tapinstall returned $($inst.ExitCode)"
	exit 3
}

# cerca i dispositivi tap0901 dopo l'install; trova il nuovo confrontando i PNPIDs
$after = Get-CimInstance -ClassName Win32_NetworkAdapter | Where-Object { $_.ServiceName -eq 'tap0901' } |
				Select-Object PNPDeviceID, Name

# primo tentativo: device con PNP non presente in $prevPNP
$new = $after | Where-Object { $prevPNP -notcontains $_.PNPDeviceID } | Select-Object -First 1

if (-not $new) {
	Write-Warning "No new PNP comparing. Getting the first tap0901 instance available."
	$new = $after | Select-Object -First 1
}

if (-not $new) {
	Write-Error "No tap0901 device found after install."
	exit 5
}

Write-Output "Selected device: PNP=$($new.PNPDeviceID) Description/Name=$($new.Name)"

# Map al nome "Name" di Get-NetAdapter (InterfaceDescription -> Name)
$iface = $null
try {
	$iface = Get-NetAdapter | Where-Object { $_.InterfaceDescription -eq $new.Name } | Select-Object -ExpandProperty Name -ErrorAction SilentlyContinue
} catch {}

if (-not $iface) {
	# tentativo fuzzy: match parziale (aiuta con descrizioni che contengono dettagli)
	try {
		$escaped = [regex]::Escape($new.Name)
		$iface = Get-NetAdapter | Where-Object { $_.InterfaceDescription -match $escaped } | Select-Object -First 1 -ExpandProperty Name -ErrorAction SilentlyContinue
	} catch {}
}

if (-not $iface) {
	Write-Warning "Impossible to map the network interface before rename. The device exists but the mapping is failed."
	exit 4
}

Write-Output "Renaming adapter '$iface' -> 'TAP-HT Portal' ..."
try {
	Rename-NetAdapter -Name $iface -NewName 'TAP-HT Portal' -Confirm:$false -ErrorAction Stop
	Write-Output "Rename ok."
} catch {
	Write-Error "Error during Rename-NetAdapter: $_"
	exit 4
}

Set-Location $oldLocation

exit 0