# Self-elevate the script if required
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
 if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
  $CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
  Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
  Exit
 }
}

cd $PSScriptRoot

Write-Host "Checking for port config"
$DefaultPort = 5201
$PortConfigFile = Get-ChildItem -Filter "*.port"
if ($PortConfigFile.Count -gt 0){
    $Port = $PortConfigFile[0].Name.Split('.')[0]
    if ($Port -match "^[\d\.]+$"){
        Write-Host "   -> Config file found, port set to $Port." -ForegroundColor Green
    }
    else{
        $Port = $DefaultPort
        Write-Host "   -> Config file found, but not well formatted. Port defaulting to $Port. Remember you can add a xxxx.port-File in the directory to set it to port xxxx." -ForegroundColor Red
    }
}
else{
    $Port = $DefaultPort
    Write-Host "   -> No Config file found, port defaulting to $Port. Remember you can add a xxxx.port-File in the directory to set it to port xxxx." -ForegroundColor Yellow
}


Write-Host "Firewallcheck"
$iCountInboundRules = 0
$iCountInboundRules = (Get-NetFirewallRule | Where { $_.DisplayName -like "iPerf*" -and $_.Direction -eq "Inbound" -and $_.Action -eq "Allow"} | measure).Count
if($iCountInboundRules -lt 1){
	Write-Host "   -> Adding Inbound Firewall Rule..." -ForegroundColor Cyan
	New-NetFirewallRule -DisplayName "iPerf TCP" -Direction Inbound -LocalPort $Port -Protocol "TCP" -Action Allow -Group "iPerf" -Description "Inbound iPerf TCP port" | Out-Null
	New-NetFirewallRule -DisplayName "iPerf UDP" -Direction Inbound -LocalPort $Port -Protocol "UDP" -Action Allow -Group "iPerf" -Description "Inbound iPerf UDP port" | Out-Null
	Write-Host "   -> Inbound Firewall Rule added." -ForegroundColor Green
}
else{
    Write-Host "   -> Inbound Firewall Rules already created." -ForegroundColor Green
}
Write-Host "Firewallcheck done."

Write-Host "Starting iPerf."
.\iperf3.exe -s -p $Port