##/*********************************************************************************
##Author                :   Vishnu S
##Purpose               :   Display the specific activities from audit log in O365
##Created               :   24/01/2018
##Modified By	        : 
##/*********************************************************************************

[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

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

$rpArr=$rpmea.Split('#')
$reportingNam=$rpArr[0]
$meaperiod=$rpArr[1]

$rptPath='O365/'+$reportingNam
try{

    $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
    $DateFormat = $CultureDateTimeFormat.ShortDatePattern
    $TimeFormat = $CultureDateTimeFormat.LongTimePattern
    $DateTimeFormat = "$DateFormat $TimeFormat"
 
    $UserDisplayName=@{}
    $sysDateFmt=(Get-Date).ToUniversalTime()
    $sysDat=$sysDateFmt.AddMinutes(-$meaperiod)
    $flag=$true
    $uniqUserId=@{}
    $splitedUsrId=$UserId.split('<')

    $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
    foreach($b in $a){
    	$dateCreated =[DateTime]::ParseExact(($b.CreationDate),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        if($dateCreated -ge $sysDat){
            $activity = $b.AuditData | ConvertFrom-Json | select *          
            if($activity -ne "" -and $activity -ne $null){
                $key=$activity.UserId+'!'+$activity.Operation
                if($uniqUserId.ContainsKey($key)){
                    $uniqUserId[$key]=[int]$uniqUserId[$key]+1
                }else{
                    $uniqUserId.Add($key,1) 
                }
            }
        }
    }
    if($uniqUserId -ne $null){
        $tests=Get-content -Path $egurkhaPath'\agent\config\eg_tests.ini'
        $posiOptName=@{}
        $firstEntry=$false
        foreach($testsini in $tests){
            if($testsini -eq '[O365_Activities]'){
                $firstEntry=$true
            }
            elseif($testsini -eq '[O365_Subscriptions]'){
                $firstEntry=$false
            }
            if($firstEntry){
                if($testsini -ne '[O365_Activities]'){
                    $valAndOpt= $testsini.Split("=")[1].Split(",")
                    foreach($valOpt in $valAndOpt){
                        $posvthOpt= $valOpt.Split("#")
                        $posiOptName.Add($posvthOpt[0],$posvthOpt[2])
                    }
                }
            }
        }
        foreach($UsrId in $splitedUsrId){
            $array=@()
            $uniopeAllUser=@{}
            $specuser_oper=@{}
            if($UsrId.StartsWith('All_User')){
                $UsrId=$UsrId.Substring('All_User'.Length+1)
                $userarr=$UsrId -split ':'
                foreach($userpos in $userarr){
                    $array+=@($posiOptName[$userpos])
                }
            $flag=$true
            }else{
                $userarr=$UsrId
                $flag=$false
            }
            if($flag){
                foreach($key in $uniqUserId.keys){
                    $useropr=$key -split '!'
                    $oper_name=$useropr[1]
                    if($array.Contains($oper_name)){
                        if($uniopeAllUser.Contains($oper_name)){
                            $temp=$uniqUserId[$key]
                            $uniopeAllUser[$oper_name]+=$temp
                        }else{
                            $uniopeAllUser.Add($oper_name,$uniqUserId[$key])
                        }
                    }
                }
                foreach($key in $uniopeAllUser.keys){
                    write-host 'Measureline All Users'~ $key ~ $uniopeAllUser[$key]
                    foreach($b in $a){
                        $dateCreated =[DateTime]::ParseExact(($b.CreationDate),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                        $activity = $b.AuditData | ConvertFrom-Json | select * 
                        if($activity.Operation -eq $key -and $dateCreated -ge $sysDat){
                            Write-Host 'DDline All Users ~' $key ~ $activity
                        }
                    }
                }
            }
            else{
                $operarr=$userarr -split "!"
                if($operarr -ne $null){
                    $operlist=$operarr[1] -split ":"
                    foreach($userpos in $operlist){
                        $array+=@($posiOptName[$userpos])
                    }
                    $specuser_oper.Add($operarr[0],$array)
                }
                foreach($key in $uniqUserId.keys){
                    $useropr=$key -split '!'
                    $user_name=$useropr[0]
                    $opr_name=$useropr[1]
                    if($specuser_oper.ContainsKey($user_name)){
                        $temparr=$specuser_oper[$user_name]
                        if($temparr.Contains($opr_name)){ # review and to be change
                            Write-Host 'Measureline' $UrName ~ $opr_name ~ $uniqUserId[$key]
                            foreach($b in $a){
                                $dateCreated =[DateTime]::ParseExact(($b.CreationDate),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                                $activity = $b.AuditData | ConvertFrom-Json | select * 
                                if($activity.UserId -eq $user_name -and $activity.Operation -eq $opr_name -and $dateCreated -ge $sysDat){
                                    Write-Host 'DDline' $user_name ~ $opr_name ~ $activity
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
catch{    
        $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	    Write-error "Exception Occured in O365 Specific AuditLog -  $exceptionmsg" 
}