[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value
$egurkhaPath=$egInstallpath.Value.ToString()
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy
clear 

$TestInputs=$args

$reportingname='EXO\'+$TestInputs[0]
try{
    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "mailbox" -keyFileName "kmailbox" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $MailboxesDetails= import-csv $csvfile
    Remove-Item $csvfile
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'mailbox' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kmailbox' -InputFile $readfiles[4]
    Write-Host 'ReadFile:'$readfiles[3]
    }
    catch [System.Management.Automation.RuntimeException] {
        Write-Error -Message "File not found. The $reportingname location does not contain mailbox files."
    }
    catch{
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }

Try{
    $readArr =Eg-ReadFile -ComntRptPath $reportingname -FileName "O365msolUsr" -keyFileName "kO365msolUsr" -EgPath $egurkhaPath
    $unProtctMUsr =$readArr[1] -replace (".csv",".dat") 
    $musrPath =Unprotect-File $unProtctMUsr -Algorithm AES -KeyAsPlainText $readArr[0]	
    $msoluserS = import-csv $musrPath
    Remove-Item $musrPath
    Write-Host 'ReadFile:'$readArr[3]
    }Catch{}
    
    Eg-DeleteFiles -FilePath $readArr[2] -Pattern 'O365msolUsr' -InputFile $readArr[3]
    Eg-DeleteFiles -FilePath $readArr[2] -Pattern 'kO365msolUsr' -InputFile $readArr[4]

	$Datacenter = @{}
	$Datacenter["AF"]=@("","Afghanistan")
    $Datacenter["AL"]=@("","Albania")
    $Datacenter["DZ"]=@("","Algeria")
    $Datacenter["AS"]=@("","American Samoa")
    $Datacenter["AD"]=@("","Andorra")
    $Datacenter["AO"]=@("","Angola")
    $Datacenter["AI"]=@("","Anguilla")
    $Datacenter["AQ"]=@("","Antarctica")
    $Datacenter["AG"]=@("","Antigua and Barbuda")
    $Datacenter["AR"]=@("","Argentina")
    $Datacenter["AM"]=@("","Amsterdam, Netherlands")
    $Datacenter["AW"]=@("","Aruba")
    $Datacenter["AU"]=@("","Australia")
    $Datacenter["AT"]=@("","Austria")
    $Datacenter["AZ"]=@("","Azerbaijan")
    $Datacenter["BS"]=@("","Bahamas")
    $Datacenter["BH"]=@("","Bahrain")
    $Datacenter["BD"]=@("","Bangladesh")
    $Datacenter["BB"]=@("","Barbados")
    $Datacenter["BY"]=@("","Belarus")
    $Datacenter["BE"]=@("","Belgium")
    $Datacenter["BZ"]=@("","Belize")
    $Datacenter["BJ"]=@("","Benin")
    $Datacenter["BM"]=@("","Bermuda")
    $Datacenter["BT"]=@("","Bhutan")
    $Datacenter["BO"]=@("","Bolivia")
    $Datacenter["BQ"]=@("","Bonaire")
    $Datacenter["BA"]=@("","Bosnia and Herzegovina")
    $Datacenter["BW"]=@("","Botswana")
    $Datacenter["BV"]=@("","Bouvet Island")
    $Datacenter["BR"]=@("","Brazil")
    $Datacenter["IO"]=@("","British Indian Ocean Territory")
    $Datacenter["BN"]=@("","Brunei Darussalam")
    $Datacenter["BG"]=@("","Bulgaria")
    $Datacenter["BF"]=@("","Burkina Faso")
    $Datacenter["BI"]=@("","Burundi")
    $Datacenter["KH"]=@("","Cambodia")
    $Datacenter["CM"]=@("","Cameroon")
    $Datacenter["CA"]=@("","Canada")
    $Datacenter["CV"]=@("","Cape Verde")
    $Datacenter["KY"]=@("","Cayman Islands")
    $Datacenter["CF"]=@("","Central African Republic")
    $Datacenter["TD"]=@("","Chad")
    $Datacenter["CL"]=@("","Chile")
    $Datacenter["CN"]=@("","China")
    $Datacenter["CX"]=@("","Christmas Island")
    $Datacenter["CC"]=@("","Cocos (Keeling) Islands")
    $Datacenter["CO"]=@("","Colombia")
    $Datacenter["KM"]=@("","Comoros")
    $Datacenter["CG"]=@("","Congo")
    $Datacenter["CD"]=@("","Democratic Republic of the Congo")
    $Datacenter["CK"]=@("","Cook Islands")
    $Datacenter["CR"]=@("","Costa Rica")
    $Datacenter["HR"]=@("","Croatia")
    $Datacenter["CU"]=@("","Cuba")
    $Datacenter["CW"]=@("","Curacao")
    $Datacenter["CY"]=@("","Cyprus")
    $Datacenter["CZ"]=@("","Czech Republic")
    $Datacenter["CI"]=@("","Cote d'Ivoire")
    $Datacenter["DK"]=@("","Denmark")
    $Datacenter["DJ"]=@("","Djibouti")
    $Datacenter["DM"]=@("","Dominica")
    $Datacenter["DO"]=@("","Dominican Republic")
    $Datacenter["EC"]=@("","Ecuador")
    $Datacenter["EG"]=@("","Egypt")
    $Datacenter["SV"]=@("","El Salvador")
    $Datacenter["GQ"]=@("","Equatorial Guinea")
    $Datacenter["ER"]=@("","Eritrea")
    $Datacenter["EE"]=@("","Estonia")
    $Datacenter["ET"]=@("","Ethiopia")
    $Datacenter["FK"]=@("","Falkland Islands (Malvinas)")
    $Datacenter["FO"]=@("","Faroe Islands")
    $Datacenter["FJ"]=@("","Fiji")
    $Datacenter["FI"]=@("","Finland")
    $Datacenter["FR"]=@("","France")
    $Datacenter["GF"]=@("","French Guiana")
    $Datacenter["PF"]=@("","French Polynesia")
    $Datacenter["TF"]=@("","French Southern Territories")
    $Datacenter["GA"]=@("","Gabon")
    $Datacenter["GM"]=@("","Gambia")
    $Datacenter["GE"]=@("","Georgia")
    $Datacenter["DE"]=@("","Germany")
    $Datacenter["GH"]=@("","Ghana")
    $Datacenter["GI"]=@("","Gibraltar")
    $Datacenter["GR"]=@("","Greece")
    $Datacenter["GL"]=@("","Greenland")
    $Datacenter["GD"]=@("","Grenada")
    $Datacenter["GP"]=@("","Guadeloupe")
    $Datacenter["GU"]=@("","Guam")
    $Datacenter["GT"]=@("","Guatemala")
    $Datacenter["GG"]=@("","Guernsey")
    $Datacenter["GN"]=@("","Guinea")
    $Datacenter["GW"]=@("","Guinea-Bissau")
    $Datacenter["GY"]=@("","Guyana")
    $Datacenter["HT"]=@("","Haiti")
    $Datacenter["HM"]=@("","Heard Island and McDonald Islands")
    $Datacenter["VA"]=@("","Holy See (Vatican City State)")
    $Datacenter["HN"]=@("","Honduras")
    $Datacenter["HK"]=@("","Hong Kong")
    $Datacenter["HU"]=@("","Hungary")
    $Datacenter["IS"]=@("","Iceland")
    $Datacenter["IN"]=@("","India")
    $Datacenter["ID"]=@("","Indonesia")
    $Datacenter["IR"]=@("","Islamic Republic of Iran")
    $Datacenter["IQ"]=@("","Iraq")
    $Datacenter["IE"]=@("","Ireland")
    $Datacenter["IM"]=@("","Isle of Man")
    $Datacenter["IL"]=@("","Israel")
    $Datacenter["IT"]=@("","Italy")
    $Datacenter["JM"]=@("","Jamaica")
    $Datacenter["JP"]=@("","Japan")
    $Datacenter["JE"]=@("","Jersey")
    $Datacenter["JO"]=@("","Jordan")
    $Datacenter["KZ"]=@("","Kazakhstan")
    $Datacenter["KE"]=@("","Kenya")
    $Datacenter["KI"]=@("","Kiribati")
    $Datacenter["KP"]=@("","Democratic People's Republic of Korea")
    $Datacenter["KR"]=@("","Republic of Korea")
    $Datacenter["KW"]=@("","Kuwait")
    $Datacenter["KG"]=@("","Kyrgyzstan")
    $Datacenter["LA"]=@("","Lao People's Democratic Republic")
    $Datacenter["LV"]=@("","Latvia")
    $Datacenter["LB"]=@("","Lebanon")
    $Datacenter["LS"]=@("","Lesotho")
    $Datacenter["LR"]=@("","Liberia")
    $Datacenter["LY"]=@("","Libya")
    $Datacenter["LI"]=@("","Liechtenstein")
    $Datacenter["LT"]=@("","Lithuania")
    $Datacenter["LU"]=@("","Luxembourg")
    $Datacenter["MO"]=@("","Macao")
    $Datacenter["MK"]=@("","The Former Yugoslav Republic of Macedonia")
    $Datacenter["MG"]=@("","Madagascar")
    $Datacenter["MW"]=@("","Malawi")
    $Datacenter["MY"]=@("","Malaysia")
    $Datacenter["MV"]=@("","Maldives")
    $Datacenter["ML"]=@("","Mali")
    $Datacenter["MT"]=@("","Malta")
    $Datacenter["MH"]=@("","Marshall Islands")
    $Datacenter["MQ"]=@("","Martinique")
    $Datacenter["MR"]=@("","Mauritania")
    $Datacenter["MU"]=@("","Mauritius")
    $Datacenter["YT"]=@("","Mayotte")
    $Datacenter["MX"]=@("","Mexico")
    $Datacenter["FM"]=@("","Federated States of Micronesia")
    $Datacenter["MD"]=@("","Republic of Moldova")
    $Datacenter["MC"]=@("","Monaco")
    $Datacenter["MN"]=@("","Mongolia")
    $Datacenter["ME"]=@("","Montenegro")
    $Datacenter["MS"]=@("","Montserrat")
    $Datacenter["MA"]=@("","Morocco")
    $Datacenter["MZ"]=@("","Mozambique")
    $Datacenter["MM"]=@("","Myanmar")
    $Datacenter["NA"]=@("","Namibia")
    $Datacenter["NR"]=@("","Nauru")
    $Datacenter["NP"]=@("","Nepal")
    $Datacenter["NL"]=@("","Netherlands")
    $Datacenter["NC"]=@("","New Caledonia")
    $Datacenter["NZ"]=@("","New Zealand")
    $Datacenter["NI"]=@("","Nicaragua")
    $Datacenter["NE"]=@("","Niger")
    $Datacenter["NG"]=@("","Nigeria")
    $Datacenter["NU"]=@("","Niue")
    $Datacenter["NF"]=@("","Norfolk Island")
    $Datacenter["MP"]=@("","Northern Mariana Islands")
    $Datacenter["NO"]=@("","Norway")
    $Datacenter["OM"]=@("","Oman")
    $Datacenter["PK"]=@("","Pakistan")
    $Datacenter["PW"]=@("","Palau")
    $Datacenter["PS"]=@("","State of Palestine")
    $Datacenter["PA"]=@("","Panama")
    $Datacenter["PG"]=@("","Papua New Guinea")
    $Datacenter["PY"]=@("","Paraguay")
    $Datacenter["PE"]=@("","Peru")
    $Datacenter["PH"]=@("","Philippines")
    $Datacenter["PN"]=@("","Pitcairn")
    $Datacenter["PL"]=@("","Poland")
    $Datacenter["PT"]=@("","Portugal")
    $Datacenter["PR"]=@("","Puerto Rico")
    $Datacenter["QA"]=@("","Qatar")
    $Datacenter["RO"]=@("","Romania")
    $Datacenter["RU"]=@("","Russian Federation")
    $Datacenter["RW"]=@("","Rwanda")
    $Datacenter["RE"]=@("","Reunion")
    $Datacenter["BL"]=@("","Saint Barthelemy")
    $Datacenter["SH"]=@("","Saint Helena")
    $Datacenter["KN"]=@("","Saint Kitts and Nevis")
    $Datacenter["LC"]=@("","Saint Lucia")
    $Datacenter["MF"]=@("","Saint Martin (French part)")
    $Datacenter["PM"]=@("","Saint Pierre and Miquelon")
    $Datacenter["VC"]=@("","Saint Vincent and the Grenadines")
    $Datacenter["WS"]=@("","Samoa")
    $Datacenter["SM"]=@("","San Marino")
    $Datacenter["ST"]=@("","Sao Tome and Principe")
    $Datacenter["SA"]=@("","Saudi Arabia")
    $Datacenter["SN"]=@("","Senegal")
    $Datacenter["RS"]=@("","Serbia")
    $Datacenter["SC"]=@("","Seychelles")
    $Datacenter["SL"]=@("","Sierra Leone")
    $Datacenter["SG"]=@("","Singapore")
    $Datacenter["SX"]=@("","Sint Maarten (Dutch part)")
    $Datacenter["SK"]=@("","Slovakia")
    $Datacenter["SI"]=@("","Slovenia")
    $Datacenter["SB"]=@("","Solomon Islands")
    $Datacenter["SO"]=@("","Somalia")
    $Datacenter["ZA"]=@("","South Africa")
    $Datacenter["GS"]=@("","South Georgia and the South Sandwich Islands")
    $Datacenter["SS"]=@("","South Sudan")
    $Datacenter["ES"]=@("","Spain")
    $Datacenter["LK"]=@("","Sri Lanka")
    $Datacenter["SD"]=@("","Sudan")
    $Datacenter["SR"]=@("","Suriname")
    $Datacenter["SJ"]=@("","Svalbard and Jan Mayen")
    $Datacenter["SZ"]=@("","Swaziland")
    $Datacenter["SE"]=@("","Sweden")
    $Datacenter["CH"]=@("","Switzerland")
    $Datacenter["SY"]=@("","Syrian Arab Republic")
    $Datacenter["TW"]=@("","Taiwan")
    $Datacenter["TJ"]=@("","Tajikistan")
    $Datacenter["TZ"]=@("","United Republic of Tanzania")
    $Datacenter["TH"]=@("","Thailand")
    $Datacenter["TL"]=@("","Timor-Leste")
    $Datacenter["TG"]=@("","Togo")
    $Datacenter["TK"]=@("","Tokelau")
    $Datacenter["TO"]=@("","Tonga")
    $Datacenter["TT"]=@("","Trinidad and Tobago")
    $Datacenter["TN"]=@("","Tunisia")
    $Datacenter["TR"]=@("","Turkey")
    $Datacenter["TM"]=@("","Turkmenistan")
    $Datacenter["TC"]=@("","Turks and Caicos Islands")
    $Datacenter["TV"]=@("","Tuvalu")
    $Datacenter["UG"]=@("","Uganda")
    $Datacenter["UA"]=@("","Ukraine")
    $Datacenter["AE"]=@("","United Arab Emirates")
    $Datacenter["GB"]=@("","United Kingdom")
    $Datacenter["US"]=@("","United States")
    $Datacenter["UM"]=@("","United States Minor Outlying Islands")
    $Datacenter["UY"]=@("","Uruguay")
    $Datacenter["UZ"]=@("","Uzbekistan")
    $Datacenter["VU"]=@("","Vanuatu")
    $Datacenter["VE"]=@("","Venezuela")
    $Datacenter["VN"]=@("","Viet Nam")
    $Datacenter["VG"]=@("","British Virgin Islands")
    $Datacenter["VI"]=@("","Vienna, Austria")
    $Datacenter["WF"]=@("","Wallis and Futuna")
    $Datacenter["EH"]=@("","Western Sahara")
    $Datacenter["YE"]=@("","Yemen")
    $Datacenter["ZM"]=@("","Zambia")
    $Datacenter["ZW"]=@("","Zimbabwe")
    $Datacenter["CP"]=@("","Brazil")
    $Datacenter["KA"]=@("","Japan")
    $Datacenter["OS"]=@("","Japan")
    $Datacenter["TY"]=@("","Japan")
    $Datacenter["DB"]=@("","Dublin, Ireland")
    $Datacenter["HE"]=@("","Finland")
    $Datacenter["KL"]=@("","Kuala Lumpur, Malaysia")
    $Datacenter["YQ"]=@("","Quebec City, Canada")
    $Datacenter["LO"]=@("","London, England")
	$Mailboxes = $MailboxesDetails | Where-Object {$_.RecipientTypeDetails -ne "DiscoveryMailbox"}
	#$ServerCount = ($Mailboxes | Group-Object {$_.ServerName}).count
	#$DatabaseCount = ($Mailboxes | Group-Object {$_.Database}).count
	$Mailboxes = $Mailboxes | Group-Object {$_.ServerName.SubString(0,2)} | Select @{Name="Datacenter";Expression={$_.Name}}, Count

	$Locations=@()
    $MailLocationsCount=0
	$LocationsConsolCount=0
	$usersLocationsCount=0
	
	# Not pretty error handling but allows counts to add properly when a datacenter location could not be identified from the table
	$E = $ErrorActionPreference
	$ErrorActionPreference = "SilentlyContinue"
	if($Mailboxes -ne $null -and $Mailboxes -ne ''){
        
		ForEach ($Mailbox in $Mailboxes) {
		  $Object = New-Object -TypeName PSObject
		  if($Datacenter[$Mailbox.Datacenter] -eq $null){
			$Datacenter[$Mailbox.Datacenter]=@("Unknown","Unknown")
		  }
		  $Object | Add-Member -Name 'Datacenter' -MemberType NoteProperty -Value $Mailbox.Datacenter
		  $Object | Add-Member -Name 'Region' -MemberType NoteProperty -Value $Datacenter[$Mailbox.Datacenter][0]
		  $Object | Add-Member -Name 'Location' -MemberType NoteProperty -Value $Datacenter[$Mailbox.Datacenter][1]
		  $Object | Add-Member -Name 'Count' -MemberType NoteProperty -Value $Mailbox.Count
		  $Locations += $Object
		}

		$ErrorActionPreference = $E

		$TotalMailboxes = ($Locations | Measure-Object Count -Sum).sum

		if($TotalMailboxes -eq $null ){
		  $TotalMailboxes=0
		}

		$LocationsConsolidated = $Locations | Group-Object Location | ForEach {
		      New-Object PSObject -Property @{
		      Location = $_.Name
		      Mailboxes = ("{0,9}" -f ($_.Group | Measure-Object Count -Sum).Sum)
		      }
		} | Sort-Object Count -Descending


		$ddpairs=$LocationsConsolidated | Select Location, Mailboxes
		foreach($ddline in $ddpairs){
			$LocationsConsolCount++    
			Write-Host '#DD' $ddline.Location '~!~'$ddline.Mailboxes.Trim()
		}
        $MailLocationsCount=$Locations.Count
	}
	else{
		$LocationsConsolCount = '-5'
		$MailLocationsCount= '-5'
	}
    $msoluserLocations = @()
    $msoluserS=$msoluserS | Where {$_.Userprincipalname -notlike '*#EXT#*'}

    ForEach ($msoluser in $msoluserS) {
     if($msoluser.UsageLocation -eq '' -or $Datacenter[$msoluser.UsageLocation] -eq $null){
        $Datacenter[$msoluser.UsageLocation]=@("Unknown","Unknown")
     }
	  $MsolObject = New-Object -TypeName PSObject
	  $MsolObject | Add-Member -Name 'UsageLocation' -MemberType NoteProperty -Value $Datacenter[$msoluser.UsageLocation][1]
	  $MsolObject | Add-Member -Name 'Count' -MemberType NoteProperty -Value 1
	  $msoluserLocations += $MsolObject
	}

	$usersLocationsConsolidated = $msoluserLocations | Group-Object UsageLocation | ForEach {
	      New-Object PSObject -Property @{
	      Location = $_.Name
	      Unique_Count = ("{0,9}" -f ($_.Group | Measure-Object Count -Sum).Sum)
	      }
	} | Sort-Object Unique_Count -Descending

	foreach($ddline in $usersLocationsConsolidated){
		$usersLocationsCount++    
		Write-Host '#UserLocationDD' $ddline.Location '~!~'$ddline.Unique_Count.Trim()
	}

    Write-Host '#Measure ' $MailLocationsCount '~' $LocationsConsolCount '~' $usersLocationsCount