##/*****************************************************************************
##Author                :               Guravareddy.T
##Purpose               :               O365 Dynamic Distribution Groups Types And ount
##Created               :               11/1/2017
##Modified By		: 
##/*****************************************************************************

clear
[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


$testargs=$args
$reportingname='EXO/'+$testargs[0]
$testFrequency=$testargs[1]



function Convert-UnixTime {
 
Param(
[Parameter(Mandatory=$true)][int32]$udate
) 
    # Retrieve start of UNIX Format
    $orig = (Get-Date -Year 1970 -Month 1 -Day 1 -hour 0 -Minute 0 -Second 0 -Millisecond 0) 
    # Return final time
    return $orig.AddSeconds($udate)
}
    $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
    $DateFormat = $CultureDateTimeFormat.ShortDatePattern
    $TimeFormat = $CultureDateTimeFormat.LongTimePattern
    $DateTimeFormat = "$DateFormat $TimeFormat"
try{
    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "dynamicdistgroups" -keyFileName "kdynamicdistgroups" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $recipnt= import-csv $csvfile
    Remove-Item $csvfile

    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'dynamicdistgroups' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kdynamicdistgroups' -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 recipients files."
    }
    catch{
        $errmsg=$_.Exception.Message
        $errstack=$_.Exception.StackTrace
        Write-Error -Message $errmsg
    }
        try{
            $datpos = $readfiles[3].IndexOf(".dat")
	        $length='dynamicdistgroups'.Length  
            $tmpvalue = $readfiles[3].toString().substring($length,($datpos-$length))
    		$readtime= Convert-UnixTime $tmpvalue
    		$readfiledif=NEW-TIMESPAN –Start $readtime –End (Get-Date) | Select-Object TotalMinutes
    		$dfnmb=[int]($readfiledif.TotalMinutes/(-$testFrequency))
    		$dfnmb=$dfnmb+1
    	}
    	catch{
    		$dfnmb=1
    	}
    $LastMsmtTime = ((Get-Date).AddMinutes($dfnmb*($testfrequency))).ToUniversalTime()



    try{
    $filepath=$egInstallpath.Value+'/agent/'+$reportingname+'/'
	$fileread2=Get-ChildItem -Path $filepath |Where-Object {$_.Name -like 'dynamicdistgroups*.dat'}| Sort-Object LastWriteTime -Descending | Select-Object -index 1|Select Name
	$filepath2=$filepath+$fileread2.Name
	$datpos = $fileread2.name.IndexOf(".dat")
	$length='dynamicdistgroups'.Length
	$tmpvalue = $fileread2.name.toString().substring($length,($datpos-$length)) 
	$kfileval2 = "kdynamicdistgroups"+$tmpvalue+".dat"
   	$kfile2=Get-ChildItem -Path $filepath |Where-Object {$_.Name -eq $kfileval2}| Sort-Object LastWriteTime -Descending | Select-Object -first 1|Select Name
	$kfilename2=([String]$kfile2.Name).Trim()
	$kvalue2=Get-Content -Path $filepath$kfilename2
	$decrypPath2=$filepath2 -replace (".csv",".dat") 
	$recpFile2=Unprotect-File $decrypPath2 -Algorithm AES -KeyAsPlainText $kvalue2	
	$recipnt2= import-csv $recpFile2
	Remove-Item $recpFile2

    }
    catch{
    write-error $_.Exception.Message
    $recpFile2=""
    }

	$dycdsbgrp_changedcnt =0
	$dycdsbgrp_createdcnt =0
	$dycdsbgrp_totalcnt =0
	$dycdsbgrp_orphancnt =0
	$dycdsbgrp_emptycnt =0
	$dycdsbgrp_softdeletcnt=0


	foreach($total in $recipnt)
	{
	    $total.WhenChangedUTC=$total.WhenChangedUTC.Replace('??','')
            $total.WhenCreatedUTC=$total.WhenCreatedUTC.Replace('??','')
    try{
        $total.WhenChangedUTC=[DateTime]::ParseExact(($total.WhenChangedUTC),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        $total.WhenCreatedUTC=[DateTime]::ParseExact(($total.WhenCreatedUTC),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        }catch{
            $exp=$_.Exception.Message
            Write-Error 'error occures while changing data format in 1st loop' $exp 
        }
            if($total.WhenSoftDeleted -eq "" -or $total.WhenSoftDeleted -eq $null)
            {
	        $dycdsbgrp_totalcnt++
            }
	    $status=$total.isvalid
	    if($status -eq 'True')
	    {
		$status='Active'
	    }
	    else
	    {
		 $status='Inactive'
	    }

	    if($total.ManagedBy -eq "" -or  $total.ManagedBy -eq $Null) 
	    {
		Write-Host 'dycdsbgrp_orphnedgrps##'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status '~!~' $total.GroupMemberscount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		$dycdsbgrp_orphancnt++
	    }


	    if ($total.WhenChangedUTC -ne "" -and [DateTime]($total.WhenChangedUTC) -gt $LastMsmtTime)  
	    {
		Write-Host 'dycdsbgrp_changedutc##'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status '~!~' $total.GroupMemberscount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		$dycdsbgrp_changedcnt++
	    }

	    if ($total.WhenCreatedUTC -ne "" -and [DateTime]($total.WhenCreatedUTC) -gt $LastMsmtTime)  
	    {
		Write-Host 'dycdsbgrp_createdutc##'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status '~!~' $total.GroupMemberscount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		$dycdsbgrp_createdcnt++
	    }
	    if ($total.GroupMemberscount -eq 0)
	    {
		Write-Host 'dycdsbgrp_emptygrps##'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status '~!~' '-5' '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		$dycdsbgrp_emptycnt++
	    }
        
	}
    if($recipnt2 -ne "" -and $recipnt2 -ne $null){
      foreach($total2 in $recipnt2)
      {
	    $total2.WhenChangedUTC=$total2.WhenChangedUTC.Replace('??','')
        $total2.WhenCreatedUTC=$total2.WhenCreatedUTC.Replace('??','')
        try{
        $total2.WhenChangedUTC=[DateTime]::ParseExact(($total2.WhenChangedUTC),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        $total2.WhenCreatedUTC=[DateTime]::ParseExact(($total2.WhenCreatedUTC),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        }catch{
        $excp=$_.Exception.Message
        Write-Error 'error occures while changing data format in 2nd loop' $excp
        }

        $status=$total2.isvalid
	    if($status -eq 'True')
	    {
		$status='Active'
	    }
	    else
	    {
		 $status='Inactive'
	    }        
        $smtpadrs=$total2.PrimarySmtpAddress
        $bolean=$false
        foreach($total in $recipnt)
	    {
        
            if($smtpadrs -eq $total.PrimarySmtpAddress)
            {
                $bolean=$true
	        }
        }

        if($recipnt2 -ne "" -and $recipnt2 -ne $null -and $bolean -eq $false)
        {
            Write-Host 'dycdsbgrp_softdeleted##'$total2.DisplayName'~!~'$total2.PrimarySmtpAddress'~!~'$total2.Alias'~!~'$status '~!~' $total2.GroupMemberscount '~!~'$total2.WhenChangedUTC'~!~'$total2.WhenCreatedUTC
	        $dycdsbgrp_softdeletcnt++
	    }
       }
     }

	Write-Host 'dycdsbgrp_changedcnt' $dycdsbgrp_changedcnt 
	Write-Host 'dycdsbgrp_createdcnt' $dycdsbgrp_createdcnt 
	Write-Host 'dycdsbgrp_TotalCount' $dycdsbgrp_totalcnt 
	Write-Host 'dycdsbgrp_ownlesscount' $dycdsbgrp_orphancnt 
	Write-Host 'dycdsbgrp_membcount' $dycdsbgrp_emptycnt 
	Write-Host 'dycdsbgrp_softcount' $dycdsbgrp_softdeletcnt 