[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]
$showUsrMalwareMails=$testargs[1]
$userName=$testargs[2]
$startTime=$testargs[3]
$startTime=$startTime.Replace('_',' ')
try{
    $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
    $DateFormat = $CultureDateTimeFormat.ShortDatePattern
    $TimeFormat = $CultureDateTimeFormat.LongTimePattern
    $DateTimeFormat = "$DateFormat $TimeFormat"

    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "malware" -keyFileName "kmalware" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $Malwaredetail= import-csv $csvfile
    Remove-Item $csvfile
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'malware' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kmalware' -InputFile $readfiles[4]
    }
    catch [System.Management.Automation.RuntimeException] {
        Write-Error -Message "File not found. The $reportingname location does not contain malware files."
    }
    catch{
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }
$Malwaredetail= $Malwaredetail | Sort-Object {[DateTime]::ParseExact($_.'Date',$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)}  -Descending
$LastDateMalware = $Malwaredetail |select -Property Date -First 1   
#Malware Variables
    $InEvnType= @{}
    $OutEvnType= @{}
    $InEvnTypeCnt= @{}
    $OutEvnTypeCnt= @{}
    $InEvnSenSize= @{}
    $OutEvnSenSize= @{}
    $InEvnSize= @{}
    $OutEvnSize= @{}
    $UniqSen= @{}
    $UniqRec= @{}
    $UniqSenCnt= @{}
    $UniqRecCnt= @{}
    $EvnType= New-Object System.Collections.ArrayList
	$reg="^\d*/\d*/[2-9]\d\d\d \d*:\d*:\d*$"
    
    $Malwaredetail=$Malwaredetail| where{$_.MalwareName -ne ''}
	if($Malwaredetail -ne $null){
	       foreach($Malwaredata in $Malwaredetail){
            $entryflg=$false
            if($startTime -ne $null -and $startTime -ne ''){
                $MalwareDate = [DateTime]::ParseExact($Malwaredata.Date,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                $prevTime = [DateTime]::ParseExact($startTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                if($MalwareDate -gt $prevTime){
                    $entryflg=$true
                }
            }
            else{
                $entryflg=$true
            }
            if($entryflg){
                if(!$showUsrMalwareMails)
                {
                    if( ($Malwaredata.SenderAddress).toString().toLower().trim() -eq $userName.toString().toLower().trim() -or ($Malwaredata.RecipientAddress).toString().toLower().trim() -eq $userName.toString().toLower().trim() )
                    {
                        continue;
                    }
                } 
                $mName=$Malwaredata.MalwareName
 			    $TotMsgSizemb=[math]::round($Malwaredata.MessageSize /1mb, 4)
                $TotMsgSizegb=[math]::round($Malwaredata.MessageSize /1gb, 4)
			    if(-not $EvnType.Contains($mName)){
			        $EvnType.Add($mName)
		        }
                $totMsgSizeky=$mName+'#'+$Malwaredata.SenderAddress+'~!~'+$Malwaredata.RecipientAddress+'~!~'+$Malwaredata.FileName
                $uniqSendKy=$mName+'#'+$Malwaredata.SenderAddress
                $uniqRecipKy=$mName+'#'+$Malwaredata.RecipientAddress
                if($Malwaredata.Direction -eq 'Inbound'){       
                    if($InEvnType.Contains($mName)){
                         $InEvnTypeCnt[$mName]+=1
                         $tmposht=$InEvnType[$mName]
			                if($tmposht.Contains($totMsgSizeky)){
                                $tmposht[$totMsgSizeky]+=$TotMsgSizemb
                            }
                            else{
                                $tmposht.Add($totMsgSizeky,$TotMsgSizemb)
                            }
                    }
                    else{
                         $InEvnTypeCnt.Add($mName,1)
                         $InSendEvnType= @{}
                         $InSendEvnType.Add($totMsgSizeky,$TotMsgSizemb)       
			             $InEvnType.Add($mName,$InSendEvnType)
			        }
			            if($InEvnSize.Contains($mName)){
				            $InEvnSize[$mName]+=$TotMsgSizegb 
			            }else{
			                $InEvnSize.Add($mName,$TotMsgSizegb)
			            }
			            if($InEvnSenSize.Contains($totMsgSizeky)){
				            $InEvnSenSize[$totMsgSizeky]+=1 
			            }else{
			                $InEvnSenSize.Add($totMsgSizeky,1)
			            }
		            }
                else{
			        if($OutEvnType.Contains($mName)){
                        $OutEvnTypeCnt[$mName]+=1
                        $tmposht=$OutEvnType[$mName]
		                if($tmposht.Contains($totMsgSizeky)){
                            $tmposht[$totMsgSizeky]+=$TotMsgSizemb
                        }
                        else{
                            $tmposht.Add($totMsgSizeky,$TotMsgSizemb)
                        }
                    }
                    else{
                         $OutEvnTypeCnt.Add($mName,1)
                         $OutSendEvnType= @{}
                         $OutSendEvnType.Add($totMsgSizeky,$TotMsgSizemb)       
			             $OutEvnType.Add($mName,$OutSendEvnType)
			        }

			        if($OutEvnSize.Contains($mName)){
				        $OutEvnSize[$mName]+=$TotMsgSizegb
			        }else{
				        $OutEvnSize.Add($mName,$TotMsgSizegb)
			        }
                    if($OutEvnSenSize.Contains($totMsgSizeky)){
				        $OutEvnSenSize[$totMsgSizeky]+=1
			        }else{
				        $OutEvnSenSize.Add($totMsgSizeky,1)
			        }
		        }
		    if($UniqSen.Contains($uniqSendKy)){
			    $tmpSenAdd=$UniqSen[$uniqSendKy]
                $tmpSenAdd[0]+=1
                $tmpSenAdd[1]+=$TotMsgSizemb
            }
		    else{
			    $SndAdd= 1,$TotMsgSizemb
			    $UniqSen.Add($uniqSendKy,$SndAdd)
		    }
		    if($UniqRec.Contains($uniqRecipKy)){
			    $tmpRecAdd=$UniqRec[$uniqRecipKy]
                $tmpRecAdd[0]+=1
                $tmpRecAdd[1]+=$TotMsgSizemb
            }
		    else{
                [double[]]$RecAdd =1,$TotMsgSizemb
			    $UniqRec.Add($uniqRecipKy,$RecAdd)
		    }
		    if($UniqSenCnt.Contains($mName)){
			    $tmpSenAddList=$UniqSenCnt[$mName]
			    if($tmpSenAddList -notcontains ($Malwaredata.SenderAddress)){
			        $tmpSenAddList.Add($Malwaredata.SenderAddress)
			    }
		    }
		    else{
			    $SndAddList =  New-Object System.Collections.ArrayList
			    $SndAddList.Add($Malwaredata.SenderAddress)
			    $UniqSenCnt.Add($mName,$SndAddList)
		    }
		    if($UniqRecCnt.Contains($mName)){
			    $tmpRecAddList=$UniqRecCnt[$mName]
			    if($tmpRecAddList -notcontains($Malwaredata.RecipientAddress)){
			        $tmpRecAddList.Add($Malwaredata.RecipientAddress)
			    }
		    }
		    else{
			    $RecAddList =  New-Object System.Collections.ArrayList
			    $RecAddList.Add($Malwaredata.RecipientAddress)
			    $UniqRecCnt.Add($mName,$RecAddList)
		    }
        }
    }
	    
	   clear
            foreach($Evntkeys in $EvnType){ 
		        $inEvntcnt=0
                $outEvntcnt=0
                $inEvntsz=0
                $outEvntsz=0
                $evntlist=$InEvnType[$Evntkeys]
		        $Outevntlist=$OutEvnType[$Evntkeys]
       		    #  $evntlist.keys | sort { $evntlist.$_ } -des | foreach {  Write-host $_ '~' $evntlist.$_ '~' $InEvnSize[$Evntkeys+'~'+$_].tostring("#.##") } | Select-Object -First 20
                if($evntlist -ne $null){
                    $in =$evntlist.keys | sort { $evntlist.$_ } -des | Select-Object -First 20
                    foreach($inky in $in) {
                        Write-host '# DDMalware In' $inky  '~!~' $evntlist[$inky].tostring("#.##").replace(',','.')     '~!~' $InEvnSenSize[$inky] 
                    }
                    $inEvntcnt=$InEvnTypeCnt[$Evntkeys]
                    $inEvntsz=$InEvnSize[$Evntkeys].tostring("#.##").replace(',','.')
                }
                
                if($Outevntlist -ne $null){            
                    $out =$Outevntlist.keys | sort { $Outevntlist.$_ } -des | Select-Object -First 20
                    foreach($outky in $out) {
                        Write-host '# DDMalware Out'$outky '~!~' $outevntlist[$outky].tostring("#.##").replace(',','.') '~!~' $OutEvnSenSize[$outky] 
                    }
                    $outEvntcnt=$OutEvnTypeCnt[$Evntkeys]
                    $outEvntsz=$OutEvnSize[$Evntkeys].tostring("#.##").replace(',','.')
                }            
                Write-Host '#Measure' $Evntkeys '~' $inEvntcnt '~' $outEvntcnt '~' $inEvntsz '~' $outEvntsz '~' $UniqSenCnt[$Evntkeys].Count'~' $UniqRecCnt[$Evntkeys].Count
            }
            $UniqSenky =$UniqSen.keys | sort {$UniqSen.$_[1]} -des | Select-Object -First 20
            $UniqRecky =$UniqRec.keys | sort {$UniqRec.$_[1]} -des | Select-Object -First 20
              foreach($Hkey in $UniqSenky){ 
                  $HValue = $UniqSen[$Hkey]
                  $HValue =$HValue -join '~!~'
                  Write-Host '# UniqueSend'$Hkey '~!~' $HValue
              }
              foreach($Hkey in $UniqRecky){
                  $HValue = $UniqRec[$Hkey]
                  $HValue =$HValue -join '~!~'
                  Write-Host '# UniqueRecv'$Hkey '~!~' $HValue
              }
    Write-Host 'LastDate:'$LastDateMalware.Date.Replace(' ','_')
    Write-Host 'ReadFile:'$readfiles[3]
}
    