##/*****************************************************************************
##Author                :     MohanRaj S
##Purpose               :     Display the list of services and their operations
##Created               :     19/10/2017
##Modified By		    :     Prabaharan.T

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

clear

$TestInputs=$args
$userName=$TestInputs[0]
$Password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUsr=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$rpmea=$TestInputs[4]


$rpArr=$rpmea.Split('#')
$reportingNam=$rpArr[0]
$meaperiod=$rpArr[1]
$allowLocalUsrAct=$rpArr[2]
$allowLocalUsr=$rpArr[3].Split(',')

$azureVal=Eg-GetAzureEnv -UserName $userName
$azureEnvArr=$azureVal.Split(',')

$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
$sessionOption = New-PSSessionOption -SkipRevocationCheck
if($proxyUsr -ne 'none' -and $proxyPass -ne 'none'){
    $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
    $sessionOption = New-PSSessionOption -SkipRevocationCheck -ProxyAccessType WinHttpConfig -ProxyAuthentication basic -ProxyCredential $proxyCred
}
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $azureEnvArr[1] -Credential $cred -Authentication Basic -AllowRedirection -SessionOption $sessionOption -WarningAction SilentlyContinue
Import-PSSession $Session  -DisableNameChecking -AllowClobber | Out-Null
$rptPath='O365/'+$reportingNam
try{
    if($Session.Availability -eq 'Available' -and $Session.State -eq 'Opened'){
        $sysDat=(Get-Date).ToUniversalTime()
        $endDat=$sysDat.AddMinutes(-60)
        $startDat=$endDat.AddMinutes(-$meaperiod)
        $uniqwrkLoad=@{}
        $uniqUserClientIpwrkLoad=@{}
	$uniqClientIp=@{}
        Try{
            $writUsrAct = Eg-WriteFile -ComntRptPath $rptPath -FileName "O365UsrAct" -keyFileName "kO365UsrAct" -EgPath $egurkhaPath
#            Search-UnifiedAuditLog  -StartDate $sysDat.AddMinutes(-$meaperiod) -EndDate $sysDat | select * |Export-Csv $writUsrAct[1]
            $AuditOutput=1
            while ($AuditOutput) {
                $AuditOutput = Search-UnifiedAuditLog -StartDate $startDat -EndDate $endDat -SessionId "1" -ResultSize 500 -SessionCommand ReturnLargeSet | Select-Object  CreationDate,AuditData 
                if($AuditOutput){
                    $AuditOutput | Export-Csv $writUsrAct[1] -NoTypeInformation -Append
                }
            }
            $null=Protect-File  $writUsrAct[1] -Algorithm AES -KeyAsPlainText $writUsrAct[0] -RemoveSource
        }Catch{
	          $egurkhaRprtPath=  $egurkhaPath+'\agent\'+$rptPath+'\'
          $fileRead=Get-ChildItem -Path $egurkhaRprtPath |Where-Object {$_.Name -like 'kO365UsrAct*.dat'}| Sort-Object LastWriteTime -Descending | Select Name -First 1
            foreach($file in $fileRead){
                    $fileName=([String]$file.Name).Trim()
                    Remove-Item $egurkhaRprtPath$fileName -Force
            }
	    }

        $readUsrAct=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365UsrAct" -keyFileName "kO365UsrAct" -EgPath $egurkhaPath
        $unProtctUsrAct=$readUsrAct[1] -replace (".csv",".dat") 
        $usrActPath=Unprotect-File $unProtctUsrAct -Algorithm AES -KeyAsPlainText $readUsrAct[0]	
        $a= import-csv $usrActPath
        Remove-Item $usrActPath
        $UniqueClientIp=@()
        $UniqueUserId=@()
        Eg-DeleteFiles -FilePath $readUsrAct[2] -Pattern 'O365UsrAct' -InputFile $readUsrAct[3]
        Eg-DeleteFiles -FilePath $readUsrAct[2] -Pattern 'kO365UsrAct' -InputFile $readUsrAct[4]
        $ExcludeActv='FileAccessed','FileCheckedIn','FileCheckedOut','FileCopied','FileDeleted','FileDeletedFirstStageRecycleBin','FileDeletedSecondStageRecycleBin','FileCheckOutDiscarded','FileDownloaded','FileModified','FileMoved','FileRenamed','FileRestored','FileUploaded','PageViewed','Search-Mailbox','UserLoggedIn','UserLoginFailed'
        foreach($b in $a){
            try{
                $activity = $b.AuditData | ConvertFrom-Json | select Workload,Operation,UserId,ClientIP
                if($activity -match '::1' -or $activity -match '<null>'){
                   continue
                }
            }catch{
            }
            $entryflag=$true
            if($allowLocalUsrAct -eq $true){
                if($allowLocalUsr -contains($activity.UserId) -and $ExcludeActv -contains($activity.Operation)){
                    $entryflag=$true
                }
            }
            else{
                if($allowLocalUsr -contains($activity.UserId) -and $ExcludeActv -contains($activity.Operation)){
                    $entryflag=$false
                }
            }
            if($entryflag -and $activity -ne "" -and $activity -ne $null -and $activity.ClientIP -ne $null){
	    		if($activity.ClientIP -ne ""){
				    $ClientIp=$activity.ClientIP
			    }else{
				    continue
			    }

           		$charCount=( $ClientIp.ToCharArray() | Where-Object {$_ -eq ':'} | Measure-Object).Count 
			    if($charCount -eq 1){
			        $ClientIp=$activity.ClientIP.Split(':')[0]
			        $ClientIp=$ClientIp.Replace("[","").Replace("]","")
			    }
			    $ClientIp=$ClientIp.Trim()
			    $uniqwrkLoadkey  = $activity.Workload+'~'+$activity.Operation.Replace(" ","_")
			    $uniqClientIpkey = $activity.Workload+'~'+$ClientIp
			    $ClientIpInnerKey= $activity.UserId+'~'+$ClientIp+'~'+$activity.Operation.Replace(" ","_")
			    $uniqUserIdkey   = $activity.Workload+'~'+$activity.UserId
			    $userIdInnerKey  = $ClientIp+'~'+$activity.UserId+'~'+$activity.Operation.Replace(" ","_")
                if(-not $UniqueUserId.Contains($activity.UserId.ToLower())){
                    $UniqueUserId+=$activity.UserId.ToLower()
                }
                if(-not $UniqueClientIp.Contains($ClientIp)){
                    $UniqueClientIp+=$ClientIp
                }
			    # Total Operations
		
			    if($uniqwrkLoad.ContainsKey($uniqwrkLoadkey)){
			        $uniqwrkLoad[$uniqwrkLoadkey]=[int]$uniqwrkLoad[$uniqwrkLoadkey]+1
			    }else{
			        $uniqwrkLoad.Add($uniqwrkLoadkey,1) 
			    }

                if($uniqUserClientIpwrkLoad.ContainsKey($activity.Workload)){
                    $tmpArray=$uniqUserClientIpwrkLoad[$activity.Workload]
                    if(-not $tmpArray[0].Contains($activity.UserId)){
                        $tmpArray[0]+=" "+$activity.UserId
                    }
                    if(-not $tmpArray[1].Contains($ClientIp)){
                        $tmpArray[1]+=" "+$ClientIp
                    }
			    }else{
                    [String[]]$myArray =$activity.UserId,$ClientIp
			        $uniqUserClientIpwrkLoad.Add($activity.Workload,$myArray)
			    }

                

			    # Client Ip

			    if($uniqClientIp.ContainsKey($activity.Workload)){
			        $tmpht=$uniqClientIp[$activity.Workload]
			        if($tmpht.ContainsKey($userIdInnerKey)){
				    $tmpht[$userIdInnerKey]=[int]$tmpht[$userIdInnerKey]+1
			        }else{
				    $tmpht.Add($userIdInnerKey,1)
			        }
			    }
			    else{
			        $tmpuniqClientIp = @{}
			        $tmpuniqClientIp.Add($userIdInnerKey,1)
			        $uniqClientIp.Add($activity.Workload,$tmpuniqClientIp) 
			    }
            }
        }
    $totOpr=0
    foreach($key in $uniqwrkLoad.keys){
        Write-Host 'Audit~' $key '~' $uniqwrkLoad[$key]
        $totOpr+=$uniqwrkLoad[$key]
    }

    foreach($key in $uniqUserClientIpwrkLoad.keys){
        Write-Host 'UsersCount~' $key '~' ($uniqUserClientIpwrkLoad[$key][0].Split(" ").Length)'~' ($uniqUserClientIpwrkLoad[$key][1].Split(" ").Length)
    }

    Write-Host 'Summary~' $totOpr ~ $uniqwrkLoad.Count ~ ($UniqueUserId | select -unique).Count ~ ($UniqueClientIp| select -unique).Count
    foreach($key in $uniqClientIp.keys){
        $uniqInnerht=$uniqClientIp[$key]
        $in =$uniqInnerht.keys | sort { $uniqInnerht.$_ } -des | Select-Object -First 30
        foreach($inky in $in) {
            Write-host 'DDAudit~' $key '#' $inky  '['$uniqInnerht[$inky]']'
        }
    }
}
Remove-PSSession $Session 
}catch
{    
	Write-Host 'Exception Occured in O365 UserActivity - ' $_.Exception.Message 
}

