$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding 
$PSDefaultParameterValues = @{'*:Encoding' = 'utf8'}

$Global:ErrorActionPreference="SilentlyContinue"

Import-Module -Name Intersight.PowerShell

[string]$ApiKeyId = $args[0]
[string]$ApiKeyFilePath = $args[1]
[string]$URL = $args[2]
[string]$BasePath = "https://intersight.com"
if ($URL -ne $null -and $URL -ne "none")
{
	[string]$BasePath = $URL
}

$ProxyHost = 'none'
$ProxyUser = 'none'
$ProxyPwd = 'none'
$ProxyHostWithPort = ''

if($args.Length -eq 5)
{
	
	$eGInstallDir = $args[3]
	# The format is https://ip:port#user#password
	$ProxyArr = $args[4].ToString().Split('#') 
	if($ProxyArr.Length -eq 3)
	{
		$ProxyHost = $ProxyArr[0]
		$ProxyUser = $ProxyArr[1]
		$ProxyPwd = $ProxyArr[2]
		$OEPath = $eGInstallDir + "\lib\OE.exe"
		$ProxyPwd = & $OEPath $ProxyPwd
		$ProxyHostArr = $ProxyHost.Split("//")
		$ProxyHostWithPort = $ProxyHostArr[1]
	}
}

if($ProxyHost -ne 'none')
{
	[system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($ProxyHost)
	if($ProxyUser -ne 'none' -and $ProxyPwd -ne 'none')
	{
		$proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $ProxyUser, $(convertto-securestring $ProxyPwd -asplaintext -force)
		[system.net.webrequest]::defaultwebproxy.credentials = $proxyCred   #[System.Net.CredentialCache]::DefaultNetworkCredentials
		[system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
	}
}

$ApiParams = @{ }
$ApiParams.add("BasePath", $BasePath)
$ApiParams.add("ApiKeyId", $ApiKeyId)
$ApiParams.add("ApiKeyFilePath", $ApiKeyFilePath)
if ($ProxyHostWithPort.length -gt 0)
{	
	$ApiParams.add("Proxy", $ProxyHostWithPort)
}
$ApiParams.add("HttpSigningHeader", @("(request-target)", "Host", "Date", "Digest"))

Set-IntersightConfiguration @ApiParams

$Fans = Get-IntersightEquipmentFanModule
if ($Fans -ne $null)
{
	foreach($F in $Fans)
	{
		Write-Host ($F.Dn,$F.OperState,$F.Presence,$F.Fans.Count,$F.Description,$F.ModuleId,$F.TrayId,$F.Revision) -Separator "#~#"
	}
}


