[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

$testargs=$args
$reportingname='EXO\'+$testargs[0]
$ExcludingNames=$testargs[1]

$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value

Function Get-MailStatsFile{
    $readfiles1=Eg-ReadFile -ComntRptPath $reportingname -FileName "statsmailbox" -keyFileName "kstatsmailbox" -EgPath $egurkhaPath
    if((Get-Item $readfiles1[1]).length -le 2kb){
        Remove-Item $readfiles1[1]
        Get-MailStatsFile
    }
    else{
        return $readfiles1
    }
}

$readMBS=Get-MailStatsFile
$mbsFileNam=$readMBS[1] -replace (".csv",".dat") 
Write-Host $readMBS[1]
$csvDatas=Unprotect-File $mbsFileNam -Algorithm AES -KeyAsPlainText $readMBS[0]	
$mbStatReports= import-csv $csvDatas
Remove-Item $csvDatas
$mailStats=$mbStatReports | select -First 1
#$isPreviousScript=[bool]($mailStats.PSobject.Properties.name -match "PrimarySmtpAddress")
<#
if($isPreviousScript){
    $ErrorCount=0
    $readfiles=0
    $readfiles1=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]
        $TotMailbxcnt= 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]
    }
    catch [System.Management.Automation.RuntimeException] {
	    $ErrorCount++	
        Write-Error -Message "File not found. The $reportingname location does not contain mailbox files."
    }
    catch{
    $ErrorCount++
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }

    try{   
        $readfiles1=Get-MailStatsFile  #Eg-ReadFile -ComntRptPath $reportingname -FileName "statsmailbox" -keyFileName "kstatsmailbox" -EgPath $egurkhaPath
        $datafile1=$readfiles1[1] -replace (".csv",".dat") 
        $csvfile1=Unprotect-File $datafile1 -Algorithm AES -KeyAsPlainText $readfiles1[0]	
        $MailStatReport= import-csv $csvfile1
        Remove-Item $csvfile1
        Eg-DeleteFiles -FilePath $readfiles1[2] -Pattern 'statsmailbox' -InputFile $readfiles1[3]
        Eg-DeleteFiles -FilePath $readfiles1[2] -Pattern 'kstatsmailbox' -InputFile $readfiles1[4]
    }
    catch [System.Management.Automation.RuntimeException] {
    $ErrorCount++
        Write-Error -Message "File not found. The $reportingname location does not contain statsmailbox files."
        $MailStatReport= $null
    }
    catch{
    $ErrorCount++
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }

    if( $MailStatReport -eq $null -or  $MailStatReport -eq ''){
        write-host "#TotMailbxcnt~-5"   
        write-host "#DbSndQte~-5" 
        write-host "#DbSndRecQte~-5" 
        Write-host '#MailbxOverQte~-5'
        write-host "#TotMailbxSize~-5" 
        write-host "#inactivecnt~-5" 
        write-host "#inactiveMailbxSize~-5" 
        Write-Host '#Arrcnt~-5'
        Write-Host '#Arrmailbxsize~-5'
        Write-Host '#ClutterEnabledcnt~-5'
        Write-Host '#ClutterDisabledcnt~-5'
        Write-Host '#ArchiveWarnMailscnt~-5'
        exit
    }
    Write-Host 'ReadFile:'$readfiles[3]','$readfiles1[3]

	$inactivecnt=0
	$Arrcnt=0
	$ClutterEnabledcnt=0
	$ClutterDisabledcnt=0
	$inactiveMailbxSize=0
	$SendQte=0
	$SendRecvQte=0
	$MailbxOverQte=0
	$Arrmailbxsize=0
	$TotMailbxSize=0
	$inact=0
    $ArrWarnMailcnt=0
    $ArchiveMailboxMap=@{}
    $ArchiveWarnMailboxsMap=@{}
    if($ErrorCount -eq 0){
	    $TotMailbxcnt= $TotMailbxcnt|where {$ExcludingNames -notcontains $_.DisplayName}
	    $MailStatReport=$MailStatReport|where {$ExcludingNames -notcontains $_.DisplayName}
	    $inactive=$TotMailbxcnt|Where{$_.WasInactiveMailbox -eq $true}|Select *
	    $ShrdMailboxes = $TotMailbxcnt|Where{$_.RecipientTypeDetails -eq 'SharedMailbox'}|Select *
	    $litigationhold=$TotMailbxcnt|Where{$_.LitigationHoldEnabled -eq $true}|Select *
	    $FrwdMailbx=$TotMailbxcnt|Where{$_.DeliverToMailboxAndForward -eq $true}|Select *
	    $Inplacehold=$TotMailbxcnt|Where{$_.InPlaceHolds -eq $true -and $_.InPlaceHolds -notcontains ' '}|Select *
	    foreach($Measures in $TotMailbxcnt){
		    $StatReport= $MailStatReport| Where {$_.PrimarySMTPAddress -eq $Measures.PrimarySmtpAddress }|Select PrimarySMTPAddress,IsArchiveMailbox,IsClutterEnabled,TotalItemSize,DatabaseIssueWarningQuota,DisplayName,ItemCount,DatabaseProhibitSendQuota,DatabaseProhibitSendReceiveQuota
            if($StatReport -ne $null) {
	            if($Measures.ArchiveStatus -eq 'Active'){
		            $Arrcnt++;
		            $repTot=[String]$StatReport.TotalItemSize
		            $resBytes= $repTot.Split('(')[1].Split(' ')
		            $Arrmailbxsize+=[double]$resBytes[0].Trim()
		            $ArchiveSize=[math]::round([double]$resBytes[0] /1Gb, 4)
		            $ArchiveQuota=[double]($Measures.ArchiveQuota).Split(' ')[0]
		            $ArchivewarnQuota=[double]($Measures.ArchiveWarningQuota).Split(' ')[0]
		            $ArchiveMailboxSize=[math]::round([double]$resBytes[0] /1Gb, 4)
		            $ddstng= $Measures.Name +'~!~ ~!~ ~!~ ~!~ ~!~ ~!~ ~!~ ~!~ ~!~ '+ $Measures.ArchiveName +'~!~'+$Measures.ArchiveState +'~!~'+$ArchiveMailboxSize.tostring("#.##").replace(',','.') +'~!~'+$ArchiveQuota+'~!~'+$ArchivewarnQuota
		            $ArchiveMailboxMap[$ArchiveMailboxSize]=$ddstng
	                if($ArchiveMailboxSize -gt $ArchivewarnQuota){
	                $ArrWarnMailcnt++
	                $ArchiveWarnMailboxsMap[$ArchiveMailboxSize]=$ddstng           
	                }           
		        }
		        if($StatReport.IsClutterEnabled -eq $true){
		            $ClutterEnabledcnt++;
		        }
		        else{
		            $ClutterDisabledcnt++;
		        }

	            #Total MailBox Size
		        if($StatReport.TotalItemSize -ne $null){
		            $repOvrall=$StatReport.TotalItemSize
		            $restotBytes= $repOvrall.Split('(')[1].Split(' ')[0].Trim().Replace(“,”,””)
		            $TotMailbxSize+=[double]$restotBytes

	                #MailBox Over Quota
		            $DbWarn=[String]$Measures.IssueWarningQuota
    	            $DbWarnBytes= $DbWarn.Split('(')[1].Split(' ')[0].Trim().Replace(“,”,””)
                    if([double]$restotBytes -ge [double]$DbWarnBytes){
			            $MailbxOverQte++;
			            write-host " #ddOverWarning " $StatReport.DisplayName '~!~'  $Measures.UserPrincipalName '~!~' $StatReport.ItemCount '~!~'  $StatReport.totalItemSize  '~!~' $Measures.IssueWarningQuota  '~!~-~!~-'
		            }
		        }

                #MailBox Send Over Quota 
		        $SendQuota=[String]$Measures.ProhibitSendQuota
    	        $SendQuotaBytes= $SendQuota.Split('(')[1].Split(' ')[0].Trim().Replace(“,”,””)
		        if([double]$restotBytes -ge [double]$SendQuotaBytes){
			        $SendQte++;
			        write-host " #ddSendOverWarning " $StatReport.DisplayName '~!~'  $Measures.UserPrincipalName '~!~' $StatReport.ItemCount '~!~'  $StatReport.totalItemSize  '~!~-~!~' $Measures.ProhibitSendQuota '~!~-'
		        }
	
                #MailBox Send/recv Over Quota
		        $SendRecvQuota=[String]$Measures.ProhibitSendReceiveQuota
    	        $SendRecvQuotaBytes= $SendRecvQuota.Split('(')[1].Split(' ')[0].Trim().Replace(“,”,””)
		        if([double]$restotBytes -ge [double]$SendRecvQuotaBytes){
			        $SendRecvQte++;
			        write-host " #ddSendRecvOverWarning " $StatReport.DisplayName '~!~'  $Measures.UserPrincipalName '~!~' $StatReport.ItemCount '~!~'  $StatReport.totalItemSize  '~!~-~!~-~!~' $Measures.ProhibitSendReceiveQuota
		        }

                #Inactive MailBox Size

		        if($Measures.WasInactiveMailbox -eq $true){
                    $inactivecnt++
			        $inactSize=[String]$StatReport.TotalItemSize
			        $restotBytes= $inactSize.Split('(')[1].Split(' ')[0].Trim().Replace(“,”,””)
			        $inactiveMailbxSize+=[double]$restotBytes
		        }
	        }
        }

        foreach ( $in in $ArchiveMailboxMap.GetEnumerator() | sort -Property key  -Descending | select -first 10){
    	    Write-host '#ddArchivemails' $in.Value
        }

        foreach ( $in in $ArchiveWarnMailboxsMap.GetEnumerator() | sort -Property key  -Descending ){
    	    Write-host '#ddArchiveWarnMails' $in.Value
        }

	    $TotMailbxSize=[math]::round($TotMailbxSize /1Gb, 4)
	    $Arrmailbxsize=[math]::round($Arrmailbxsize /1Gb, 4)
		
	    # Top 10 Size DD
	    $ddlineMailbox= $MailStatReport| Select-Object DisplayName, @{name=”TotalItemSize_mb”;expression={[math]::Round((($_.TotalItemSize).Split(“(“)[1].Split(” “)[0].Replace(“,”,””)/1GB),4)}},PrimarySmtpAddress, ItemCount ,totalItemSize,DatabaseIssueWarningQuota,DatabaseProhibitSendQuota,DatabaseProhibitSendReceiveQuota | Sort-Object “TotalItemSize_mb” -Descending

	    For ($i=0; $i -lt 10; $i++) {
		    $ddline=$ddlineMailbox[$i]
			if($ddline -ne $null){
                $mailbx=$TotMailbxcnt | Where {$_.PrimarySMTPAddress -eq $Measures.PrimarySmtpAddress }|Select IssueWarningQuota,ProhibitSendQuota,ProhibitSendReceiveQuota
			    Write-Host  '#ddTop10Size '$ddline.DisplayName  '~!~' $ddline.ItemCount '~!~' $ddline.TotalItemSize_mb  '~!~' $mailbx.IssueWarningQuota.ToString().Split(" ")[0]  '~!~' $mailbx.ProhibitSendQuota.ToString().Split(" ")[0] '~!~' $mailbx.ProhibitSendReceiveQuota.ToString().Split(" ")[0]
			}
	    }
	
        #Inactive Measure DD
	    if($inactive -ne $null){
		    foreach($inact in $inactive){
		        $inactivecnt++
		        Write-Host '#ddinactive '$inact.DisplayName '~!~' $inact.PrimarySmtpAddress '~!~'$inact.WhenSoftDeleted
		    }
        }
    }
    #write-host "#TotMailbxcnt~" $TotMailbxcnt.Count
	write-host "#DbSndQte~" $SendQte
	write-host "#DbSndRecQte~" $SendRecvQte
	Write-host '#MailbxOverQte~'$MailbxOverQte
	write-host "#TotMailbxSize~" $TotMailbxSize.tostring("#.##").replace(',','.')
	write-host "#inactivecnt~" $inactivecnt
	write-host "#inactiveMailbxSize~" $inactiveMailbxSize.tostring("#.##").replace(',','.')
	Write-Host '#Arrcnt~' $Arrcnt
	Write-Host '#Arrmailbxsize~' $Arrmailbxsize.tostring("#.##").replace(',','.')
	Write-Host '#ClutterEnabledcnt~' $ClutterEnabledcnt
	Write-Host '#ClutterDisabledcnt~' $ClutterDisabledcnt
    Write-Host '#ArchiveWarnMailscnt~' $ArrWarnMailcnt
}
#>
#else{        
        $totMailBxSiz=0;$top10cnt=0;
        $iwarnQuotaCnt=0;$iwqCnt=0;
        $inActMBCnt=0;$iaCnt=0;
        $inactivMBSiz=0;
        $prohbtSndQuotaCnt=0;
        $prohbtSndRecvQCnt=0;
        $mbStatReports|Where-Object {$_.IsDeleted -eq $false}|Sort-Object{ $_.StorageUsed -as [Long] } -Descending  | ForEach-Object{
            $totMailBxSiz+=$_.StorageUsed
            if($top10cnt -lt 10){
                $top10cnt++
                $top10DD='#ddTop10Size '+$_.DisplayName+'~!~'+$_.ItemCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round(($_.IssueWarningQuota/(1024*1024*1024)),2)+'~!~'+[math]::Round(($_.ProhibitSendQuota/(1024*1024*1024)),2)+'~!~'+[math]::Round(($_.'ProhibitSend/ReceiveQuota'/(1024*1024*1024)),2)
                Write-Host $top10DD
            }

            if([long]$_.StorageUsed -ge [long]$_.IssueWarningQuota){
                $iwarnQuotaCnt++
                if($iwqCnt -lt 10){
                    $iwqCnt++
                    $iwqDD='#ddOverWarning '+$_.DisplayName+'~!~'+$_.UserPrincipalName+'~!~'+$_.ItemCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round(($_.IssueWarningQuota/(1024*1024*1024)),2)+'~!~'+[math]::Round(($_.ProhibitSendQuota/(1024*1024*1024)),2)+'~!~'+[math]::Round(($_.'ProhibitSend/ReceiveQuota'/(1024*1024*1024)),2)+'~!~-~!~-'
                    Write-Host $iwqDD
                }
            }

            if([long]$_.StorageUsed -ge [long]$_.ProhibitSendQuota){
                $prohbtSndQuotaCnt++
            }
            if([long]$_.StorageUsed -ge [long]$_.'ProhibitSend/ReceiveQuota'){
                $prohbtSndRecvQCnt++
            }       
        }

        $mbStatReports|Sort-Object{ $_.LastActivityDate -as [DateTime] } | ForEach-Object{
            if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){
                $tDat=(Get-Date).AddDays(-30)
                $ldat=[String]($_.LastActivityDate)
                $lstActDat=[DateTime]$ldat.Trim()
                if($lstActDat -lt $tDat){
                    $inActMBCnt++
                    $inactivMBSiz+=$_.StorageUsed
                    if($iaCnt -lt 10){
                        $iaCnt++
                        if($_.IsDeleted -eq $true){
                            $inactivDD='#ddinactive '+$_.DisplayName+'~!~'+$_.UserPrincipalName+'~!~'+$_.DeletedDate
                        }else{
                            $inactivDD='#ddinactive '+$_.DisplayName+'~!~'+$_.UserPrincipalName+'~!~-'
                        }
                        Write-Host $inactivDD
                    }
                }
            }
        }

        $totMailBxSiz=[math]::Round(($totMailBxSiz/(1024*1024*1024)),2)
        write-host "#TotMailbxSize~"$totMailBxSiz
        Write-host '#MailbxOverQte~'$iwarnQuotaCnt
        write-host "#inactivecnt~"$inActMBCnt
        $inactivMBSiz=[math]::Round(($inactivMBSiz/(1024*1024*1024)),2)
        write-host "#inactiveMailbxSize~"$inactivMBSiz
        Write-Host '#Arrcnt~-5'
	    Write-Host '#Arrmailbxsize~-5'
	    Write-Host '#ClutterEnabledcnt~-5'
	    Write-Host '#ClutterDisabledcnt~-5'
        write-host "#DbSndQte~"$prohbtSndQuotaCnt
		write-host "#DbSndRecQte~"$prohbtSndRecvQCnt
        Write-Host '#ArchiveWarnMailscnt~-5'
#}
