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

Set-StrictMode -Version 2
$ErrorActionPreference = 'SilentlyContinue'
Function YesNo ([boolean] $condition)
{
    if ($condition -eq $True)
    {
	    return "Yes"
    }
    Else
    {
	    return "No"
    }
}
Function TranslatePasswordOptions($pwKey)
{
	Switch($pwKey)
    {
		"Always" 	{$pwValue = "At any time"}
		"ExpiredOnly" 	{$pwValue = "When expired"}
		"Never" 	{$pwValue = "Never"}
		Default		{$pwValue = $pwKey}
	}
	return $pwValue
}
Function TranslateMethod($methodKey)
{
	Switch($methodKey)
	{
		"ExplicitForms" 	{$methodValue = "User name and password"}
		"IntegratedWindows"	{$methodValue = "Domain pass-through"}
		"CitrixAGBasic"		{$methodValue = "Pass-through from NetScaler Gateway"}
		"HttpBasic"		{$methodValue = "HTTP Basic"}
		"Certificate"		{$methodValue = "Smart card"}
		Default			{$methodValue = "(Unknown authentication method)"}
	}
	return $methodValue
}
Function TranslateNSVersion($versionKey)
{
	Switch($versionKey)
	{
		"Version10_0_69_4" 	{$versionValue = "10.0 (Build 69.4) or later"}
		"Version9x"		{$versionValue = "9.x"}
		"Version5x"		{$versionValue = "5.x"}
		Default			{$versionValue = $versionKey}
	}
	return $versionValue
}

Function TranslateHTML5Deployment($HTML5Key)
{
	Switch($HTML5Key)
	{
		"Fallback" 	{$HTML5Value = "Use Receiver for HTML5 if local install fails"}
		"Always"	{$HTML5Value = "Always use Receiver for HTML5"}
		"Off"		{$HTML5Value = "Citrix Receiver installed locally"}
		Default		{$HTML5Value = $HTML5Key}
	}
	return $HTML5Value
}

Function TranslateLogonType($logonKey)
{
	Switch($logonKey)
	{
		"DomainAndRSA" 	{$logonValue = "Domain and security token"}
		"Domain"	{$logonValue = "Domain"}
		"RSA"		{$logonValue = "Security token"}
		"SMS"		{$logonValue = "SMS authentication"}
		"SmartCard"	{$logonValue = "Smart card"}
		"None"		{$logonValue = "None"}
		Default		{$logonValue = $logonKey}
	}
	return $logonValue
}

#Add-snapins
#Exclude these snaps to avoid clash with modules
$excludedSnapins = @("Citrix.DeliveryServices.ConfigurationProvider","Citrix.DeliveryServices.ClusteredCredentialWallet.Install","Citrix.DeliveryServices.Workflow.WCF.Install" )
$availableSnapins = Get-PSSnapin -Name "Citrix.DeliveryServices.*" -Registered | Select -ExpandProperty "Name"
$loadedSnapins = Get-PSSnapin -Name "Citrix.DeliveryServices.*" -ErrorAction SilentlyContinue | Select -ExpandProperty "Name"
foreach ($snapin in $availableSnapins)
{
	if (($excludedSnapins -notcontains $snapin) -and ($loadedSnapins -notcontains $snapin))
	{
		Add-PSSnapin -Name $snapin
	}
}


#Import-modules
$dsInstallProp = Get-ItemProperty -Path HKLM:\SOFTWARE\Citrix\DeliveryServicesManagement -Name InstallDir
$dsInstallDir = $dsInstallProp.InstallDir
$dsModules = Get-ChildItem -Path "$dsInstallDir\Cmdlets" | Where { $_.FullName.EndsWith('psm1') } | foreach { $_.FullName }
foreach ($dsModule in $dsModules)
{
    Import-Module $dsModule
}

$outputfile = $args[0]

$servername = $env:computername
"Server Info" | out-file $outputfile
"#------------" | out-file $outputfile -append
"ServerName: " + $servername | out-file $outputfile -append
$serverversion = (get-DSVersion).StoreFrontVersion
"ServerVersion: " + $serverversion  | out-file $outputfile -append
$SFVersion = $serverversion
# server group
"#-------------------------------" | out-file $outputfile -append
"Processing server group starts" | out-file $outputfile -append
"#-------------------------------" | out-file $outputfile -append
$baseURL = $(get-DSHostBaseUrl).hostBaseUrl
"Base URL: " + $baseURL | out-file $outputfile -append
$clusterMemberCount = $(get-DSClusterMembersCount).MembersCount
"Number of servers: " + $clusterMemberCount | out-file $outputfile -append
if (($clusterMemberCount -gt 1) -and (($SFVersion) -ge 2.5) )
{
	$lastSource = (Get-DSClusterConfigurationUpdateState).UpdateState.LastSourceServerName
	"Last Source: " + $lastSource | out-file $outputfile -append
}
$clusterMemberNames = $(get-DSClusterMembersName).HostNames

ForEach($member in $clusterMemberNames) 
{
	If ($clusterMemberCount -gt 1)
	{
		$lastSync = $(Get-DSXdServerGroupConfigurationUpdateState $member).LastEndTime.ToString()
		"Server Name: " + $member + "`t`tSynchronization Status: " + $lastSync | out-file $outputfile -append
	}
}
"#-------------------------------" | out-file $outputfile -append
"Processing server group end" | out-file $outputfile -append
"#-------------------------------" | out-file $outputfile -append

# authentication
"Processing authentication starts" | out-file $outputfile -append
"#---------------------------------" | out-file $outputfile -append
$auth = $(Get-DSAuthenticationServicesSummary)
$tokenURL = $auth.TokenIssuerUrl + "/validate"
If($auth.UseHttps -eq $True)
{
	$status = "StoreFront using HTTPS."
	$daysToExpire = (New-TimeSpan -End $auth.IISCertificate.NotAfter).Days
}
Else
{
	$status = "StoreFront using HTTP not HTTPS."
	$daysToExpire = ""
}
"Authentication Methods" | out-file $outputfile -append
"~~~~~~~~~~~~~~~~~~~~~~~" | out-file $outputfile -append

[int]$enabledMethods = 0
ForEach ($protocol in $auth.protocols)
{
	If($protocol.DisplayInConsole -eq $True)
	{
		$methodKey = $protocol.choice
		$method = TranslateMethod($methodKey)

		Switch($protocol.enabled)
		{
			$True	{$enabled = "Yes"; ++$enabledMethods}
			Default	{$enabled = "No"}
		}
		$method + ":`t"+ $enabled | out-file $outputfile -append
	}
}

"Authentication Service" | out-file $outputfile -append
"~~~~~~~~~~~~~~~~~~~~~~~" | out-file $outputfile -append

"Token validation service: " + $tokenURL | out-file $outputfile -append
"Number of enabled methods: " + $enabledMethods | out-file $outputfile -append
"Status: " +$status | out-file $outputfile -append


"Configure Trusted Domains" | out-file $outputfile -append
"~~~~~~~~~~~~~~~~~~~~~~~~~~" | out-file $outputfile -append

$domainInfo = Get-DSExplicitCommonDataModel ($auth.SiteID) $auth.VirtualPath
$defDomain = ($domaininfo.DefaultDomain).DefaultDomain
$changePW = TranslatePasswordOptions($domainInfo.AllowUserToChangePassword)
"Domain count: " + $domainInfo.Domains.Count | out-file $outputfile -append
$TrustedDomain = "-"
If($domainInfo.Domains.Count -gt 0)
{
	"Allow users to log on from: Trusted domains only" | out-file $outputfile -append
	"Default domain: " +$defDomain | out-file $outputfile -append
	if (($SFVersion) -ge 2.6)
	{
		$showDomains = YesNo($domainInfo.ShowDomainField)
		"ShowDomains: " + $showDomains | out-file $outputfile -append
	}
	else
	{
		"ShowDomains: -" | out-file $outputfile -append
	}
	ForEach($domain in $domainInfo.Domains)
	{
		$TrustedDomain = $TrustedDomain + "," + $domain
	}
	if($TrustedDomain.startsWith("-,"))
	{
		$TrustedDomain = $TrustedDomain.substring(2)
	}
}
Else
{
	"Allow users to logon from:  Any domain" | out-file $outputfile -append
	"Default domain: -" | out-file $outputfile -append
	"ShowDomains: -" | out-file $outputfile -append
}
"Trusted domains:" + $TrustedDomain | out-file $outputfile -append

"Allow users to change passwords: "+$changePW | out-file $outputfile -append
"#-------------------------------" | out-file $outputfile -append
"Processing authentication end" | out-file $outputfile -append
"#-------------------------------" | out-file $outputfile -append

# stores
"Processing stores starts" | out-file $outputfile -append
"#-------------------------------" | out-file $outputfile -append
$accounts = @(((Get-DSGlobalAccounts).Accounts) | Sort Name)
foreach ($account in $accounts)
{
	$advertised = YesNo($account.Published)
	$store = Get-DSStoreServicesSummary | where {$_.FriendlyName -eq $account.Name}
	$friendlyName = $store.FriendlyName
	$URL = $store.Url
	if ($store.GatewayKeys.Count -gt 0)
	{
		$access = "Internal and external networks"
	}
	Else
	{
		$access = "Internal networks only"
	}

	if ($store.UseHttps -eq $True)
	{
		$status = "StoreFront using HTTPS"
	}
	Else
	{
		$status = "StoreFront using HTTP not HTTPS"
	}

	$locked = "-"
	$authenticated = "-"
	$filterTypes = "-"
	$filterKeywords = "-"
	$includeKeywords = "-"
	$excludeKeywords = "-"

	if (($SFVersion) -ge 2.5)
	{
		$locked = YesNo($store.IsLockedDown)
		$authenticated = YesNo(!$store.IsAnonymous)
		$filterTypes = Get-DSResourceFilterType $store.SiteID $store.VirtualPath
		$filterKeywords = Get-DSResourceFilterkeyword $store.SiteID $store.VirtualPath
		$includeKeywords = @($filterKeywords.Include)
		$excludeKeywords = @($filterKeywords.Exclude)
	}
	
	"General Details" | out-file $outputfile -append
	"~~~~~~~~~~~~~~~~" | out-file $outputfile -append
	"Store Name: " + $friendlyName | out-file $outputfile -append
	"Authenticated: " + $authenticated | out-file $outputfile -append
	"Advertised: " +$advertised | out-file $outputfile -append
	"Store URL: " + $URL | out-file $outputfile -append
	"Access: " +$access | out-file $outputfile -append
	"Status: " +$status | out-file $outputfile -append
	"Locked: " +$locked | out-file $outputfile -append

	" " | out-file $outputfile -append
	"Delivery Controllers" | out-file $outputfile -append
	"~~~~~~~~~~~~~~~~~~~~~~~" | out-file $outputfile -append
	$farmsets = @($store.Farmsets)
	foreach ($farmset in $farmsets)
	{
		$farms = @($farmset.Farms)
		foreach ($farm in $farms)
		{
			$farmName = $farm.FarmName 
			$farmType = $farm.FarmType
			$farmServers = $farm.Servers
			$transportType = $farm.TransportType
			$port = $farm.ServicePort
			$sslRelayPort = $farm.SSLRelayPort
			$loadBalance = YesNo($farm.LoadBalance)

			"Delivery Controller Name: " +$farmName | out-file $outputfile -append
			"Type: " +$farmType | out-file $outputfile -append
			"Servers: " + $farmServers | out-file $outputfile -append
			"XMLPort: " +$port | out-file $outputfile -append
		}
	}

	" " | out-file $outputfile -append
	"Integrate with Citrix Online" | out-file $outputfile -append
	"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" | out-file $outputfile -append

	$GoToMeeting = YesNo($store.IsGoToMeetingEnabled)
	$GotoWebinar = YesNo($store.IsGoToWebinarEnabled)
	$GoToTraining = YesNo($store.IsGoToTrainingEnabled)
	"GoToMeeting: " +$GoToMeeting | out-file $outputfile -append
	"GoToWebinar: " +$GotoWebinar | out-file $outputfile -append
	"GoToTraining: " +$GoToTraining | out-file $outputfile -append

	# remote access
	$defaultGW = ""
	$fullVPN = $False
	$vpnService = Get-DSGlobalService -ServiceRef "VPN_$($store.ServiceRef)"
	$NSGatewayAppliances = "-"
	if($vpnService.Service)
	{
		$allGws = (Get-DSGlobalGateways).Gateways
		foreach($gw in $vpnService.Service.GatewayRefs)
		{
			$vpnGws = $allGws | Where-Object { $_.ID -eq $gw.RefId }
			$Script:fullVPN = $vpnService.Service.ServiceType -eq "VPN"
			if ($gw.Default) {$defaultGW = $vpnGws.Name}
			$NSGatewayAppliances = $NSGatewayAppliances + ", " + $($vpnGws.Name)
		}
	}
	else
	{
		$service = Get-DSGlobalService -ServiceRef $store.ServiceRef
		$allGws = (Get-DSGlobalGateways).Gateways
		foreach($gw in $service.Service.GatewayRefs)
		{
			$vpnGws = $allGws | Where-Object { $_.ID -eq $gw.RefId }
			$Script:fullVPN = $service.Service.ServiceType -eq "VPN"
			if ($gw.Default) {$defaultGW = $vpnGws.Name}
			$NSGatewayAppliances = $NSGatewayAppliances + ", " + $($vpnGws.Name)
		}
	}

	if($NSGatewayAppliances.startsWith("-,"))
	{
		$NSGatewayAppliances = $NSGatewayAppliances.substring(2)
	}

	"Netscaler Gateway Appliances: " + $NSGatewayAppliances | out-file $outputfile -append

	switch ($defaultGW)
	{
		""
		{
			"Default appliance: -" | out-file $outputfile -append
			"Remote access: None" | out-file $outputfile -append
		}
		default
		{
			"Default appliance: " +$defaultGW | out-file $outputfile -append
			if ($fullVPN)
			{
				"Remote access: Full VPN Tunnel" | out-file $outputfile -append
			}
			else
			{
				"Remote access: No VPN Tunnel"| out-file $outputfile -append
			}
		}
	}
	"XXXX----------------------------------------XXXX" | out-file $outputfile -append
}
"#------------------------------------------" | out-file $outputfile -append
"Processing stores end" | out-file $outputfile -append
"#------------------------------------------" | out-file $outputfile -append
# Receiver for Web
"Processing Receiver for Web sites starts" | out-file $outputfile -append
"#------------------------------------------" | out-file $outputfile -append
$receivers = @(Get-DSWebReceiversSummary)
foreach ($receiver in $receivers)
{
	$name = $receiver.FriendlyName
	$WebUrl  = $receiver.Url

	$ClassicExpr = "-"
	$authenticated = "-"
	$HTML5version = "-"
	$authMethods = "-"
	if (($SFVersion) -ge 2.5)
	{
		$authenticated = YesNo(!$receiver.IsAnonymousStore)
		$HTML5version = $receiver.HTML5Version
		$authMethods = @($receiver.AllowedAuthMethods)
	}

	if($receiver.ClassicEnabled)
	{
		$ClassicExpr = $receiver.ClassicEnabled
	}

	$storeURL = $receiver.StoreUrl
	$aStore = $storeURL -split "/"
	$store = $aStore[$aStore.Count-1]
	$deployment = TranslateHTML5Deployment($receiver.HTML5Configuration)
	$shortcuts = Get-DSAppShortcutsTrustedUrls $receiver.SiteId $receiver.VirtualPath

	"Name: " +$name | out-file $outputfile -append
	"Website URL: " +$WebUrl | out-file $outputfile -append
	"Classic Experience Enabled: "+ $ClassicExpr | out-file $outputfile -append
	"Store: " +$store | out-file $outputfile -append
	"Store URL: " + $storeURL | out-file $outputfile -append
	"Store Authenticated: "+$authenticated | out-file $outputfile -append
	"HTML5 Version: " +$HTML5version | out-file $outputfile -append

	# "------------------ " | out-file $outputfile -append
	# $name +"#~#"+ $WebUrl +"#~#"+ $store +"#~#"+ $storeURL +"#~#"+ $authenticated +"#~#"+ $HTML5version | out-file $outputfile -append
	# "------------------ " | out-file $outputfile -append

	if(($authMethods -ne $Null) -and ($authMethods.length -gt 0) -and ($authMethods -ne "-"))
	{
		$methods = ""
		foreach ($authMethod in $authMethods)
		{
			$method = TranslateMethod($authMethod)
			$methods = $methods +", "+$method
		}
		if($methods.startsWith(","))
		{
			$methods = $methods.substring(1)
		}
		"Authentication methods: " + $methods | out-file $outputfile -append
	}
	else
	{
		"Authentication methods: -" | out-file $outputfile -append
	}

	# $finalOutputLine = $finalOutputLine+ "#~#" + $methods
	# $finalOutputLine | out-file $outputfile -append

	if (($shortcuts -ne $Null))
	{
		$TrustedURLs = @($shortcuts.TrustedUrls)
		if($TrustedURLs)
		{
			"Shortcuts to Websites: " + $TrustedURLs | out-file $outputfile -append
		}else
		{
			"Shortcuts to Websites: -"| out-file $outputfile -append
		}

		if($deployment)
		{
			"Deployment: " +$deployment | out-file $outputfile -append
		}else
		{
			"Deployment: -" | out-file $outputfile -append
		}
		# $finalOutputLine = $finalOutputLine+ "#~#" + $TrustedURLs + "#~#" +$deployment
	}
	else
	{
		"Shortcuts equal to Null" | out-file $outputfile -append
		"Shortcuts to Websites: -" | out-file $outputfile -append
		"Deployment: -" | out-file $outputfile -append
	}
	"XXXX----------------------------------------XXXX" | out-file $outputfile -append
}
"#----------------------------------------" | out-file $outputfile -append
"Processing Receiver for Web sites ends" | out-file $outputfile -append
"#----------------------------------------" | out-file $outputfile -append

# NetScaler Gateways
"Processing NetScaler Gateways starts" | out-file $outputfile -append
"#--------------------------------------" | out-file $outputfile -append
$gateways = @((Get-DSGlobalGateways).Gateways)
foreach ($gateway in $gateways)
{
	$name = $gateway.Name
	$used = "Yes"
	$url = $gateway.Address
	$NSversion = TranslateNSVersion($gateway.AccessGatewayVersion)
	$callbackURL = $gateway.CallbackURL
	$deploymentMode = $gateway.DeploymentType
	$STAs = $gateway.SecureTicketAuthorityURLs
	if ($gateway.SessionReliability -eq $True) {$sessionReliability="Yes"} Else {$sessionReliability="No"}
	if ($gateway.RequestTicketTwoSTA -eq $True) {$request2STATickets="Yes"} Else {$request2STATickets="No"}
	"Display Name: "+$name | out-file $outputfile -append
	"Used by Services: " + $used | out-file $outputfile -append

	"URL: " +$url | out-file $outputfile -append
	"Version: " +$NSversion | out-file $outputfile -append

	if($NSversion -ne "5.x")
	{
		$logonType = TranslateLogonType($gateway.Logon)
		$smartCardFallback = TranslateLogonType($gateway.SmartCardFallback)
		$subnetIPaddress = $gateway.IPAddress
		"Subnet IP address: " + $subnetIPaddress | out-file $outputfile -append
		"Logon type: " + $logonType | out-file $outputfile -append
		"Smart card fallback:" + $smartCardFallback | out-file $outputfile -append
	}
	else
	{
		"Subnet IP address: -"| out-file $outputfile -append
		"Logon type: -" | out-file $outputfile -append
		"Smart card fallback: -" | out-file $outputfile -append
	}

	"Callback URL:" +$callbackURL | out-file $outputfile -append
	"Secure Ticket Authority URLs: " + $STAs | out-file $outputfile -append	
	"Enable session reliability : " + $sessionReliability | out-file $outputfile -append
	"Request tickets from two STAs, where available: " +$request2STATickets | out-file $outputfile -append
	"XXXX----------------------------------------XXXX" | out-file $outputfile -append
}
"#------------------------------------" | out-file $outputfile -append
"Processing NetScaler Gateways ends" | out-file $outputfile -append
"#------------------------------------" | out-file $outputfile -append

# Beacons
"Processing Beacons starts" | out-file $outputfile -append
"#-------------------------------" | out-file $outputfile -append
$internalBeacons = @((Get-DSGlobalBeacons "Internal").Beacons)
$externalBeacons = @((Get-DSGlobalBeacons "External").Beacons)

if ($internalBeacons.Count -gt 0)
{
	$intrBeacons = ""
	foreach ($beacon in $internalBeacons)
	{
		$beaconAddress = ($beacon).Address
		$intrBeacons = $intrBeacons+", "+$beaconAddress
	}
	if ($intrBeacons.startsWith(","))
	{
		$intrBeacons = $intrBeacons.substring(1)
	}
	"Internal: "+$intrBeacons | out-file $outputfile -append
}

if ($externalBeacons.Count -gt 0)
{
	$extBeacons = ""
	foreach ($beacon in $externalBeacons)
	{
		$beaconAddress = ($beacon).Address
		$extBeacons = $extBeacons+", "+$beaconAddress
	}
	if ($extBeacons.startsWith(","))
	{
		$extBeacons = $extBeacons.substring(1)
	}
	"External: " +$extBeacons | out-file $outputfile -append
}
"#-------------------------------" | out-file $outputfile -append
"Processing Beacons ends" | out-file $outputfile -append
"#-------------------------------" | out-file $outputfile -append

"#EG_SCRIPT_DONE#" | out-file $outputfile -append






