##/*****************************************************************************
##Author                :               Guravareddy.T
##Purpose               :               O365 Distributed Groups Tyoes And Count
##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 "distgroups" -keyFileName "kdistgroups" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $disbtedgrp= import-csv $csvfile
    Remove-Item $csvfile
    
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'distgroups' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kdistgroups' -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='distgroups'.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 'distgroups*.dat'}| Sort-Object LastWriteTime -Descending | Select-Object -index 1|Select Name
	$filepath2=$filepath+$fileread2.Name
	$datpos = $fileread2.name.IndexOf(".dat")
	$length='distgroups'.Length
	$tmpvalue = $fileread2.name.toString().substring($length,($datpos-$length)) 
	$kfileval2 = "kdistgroups"+$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 -Message "File not found. The $reportingname location does not contain 2nd recipient file for getting deleted groups.[error] $_.Exception.Message "
    $recpFile2=""
    }


	$dsgrp_groups=@{}

	foreach($total in $disbtedgrp)
	{
	    $grouptype=($total.GroupType).Trim()
	    if($grouptype.StartsWith('Universal,'))
	    {

		$grouptype=$grouptype.Substring(('Universal,'.Length)).Trim()
	    }
	    if($dsgrp_groups.ContainsKey($grouptype))
	    {
	    }
	    else
	    {
		Write-Host 'grouptype##' $grouptype
		$dsgrp_groups[$grouptype]=@{}
		$dsgrp_groups[$grouptype]['dsgrp_changedcnt'] = 0
		$dsgrp_groups[$grouptype]['dsgrp_createdcnt'] = 0
		$dsgrp_groups[$grouptype]['dsgrp_totalcnt'] = 0
		$dsgrp_groups[$grouptype]['dsgrp_ownlesscnt'] = 0
		$dsgrp_groups[$grouptype]['dsgrp_emptycnt'] = 0
		$dsgrp_groups[$grouptype]['dsgrp_softdetedcnt']=0

	    }
	}


	foreach($total in $disbtedgrp)
	{
       $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 
       }

	    $grouptype=($total.GroupType).Trim()
        $intialgrptype=$grouptype
	    if($grouptype.StartsWith('Universal,'))
	    {

		$grouptype=$grouptype.Substring(('Universal,'.Length)).Trim()
        

	    }
	    if($dsgrp_groups.ContainsKey($grouptype))
	    {

		$status=$total.isvalid
		if($status -eq 'True')
		{
			$status='Active'
		}
		else
		{
			$status='Inactive'
		}
	     
		$dsgrp_groups[$grouptype]['dsgrp_totalcnt']++
		if($total.ManagedBy -eq "" -or $total.ManagedBy -eq $Null )
		{
		    Write-Host $grouptype 'dsgrp_orphndgrp#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberscount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		    $dsgrp_groups[$grouptype]['dsgrp_ownlesscnt']++
		}
		if ($total.WhenChangedUTC -ne "" -and [DateTime]($total.WhenChangedUTC) -gt $LastMsmtTime)  
		{
		    Write-Host $grouptype 'dsgrp_changedutc#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberscount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		    $dsgrp_groups[$grouptype]['dsgrp_changedcnt']++
		}

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

		if ($total.GroupMemberscount -eq 0)
		{
		    Write-Host $grouptype 'dsgrp_emptygrp#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' '-5' '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		    $dsgrp_groups[$grouptype]['dsgrp_emptycnt']++
		}

        if($intialgrptype.StartsWith('Universal,'))
        {
            $grouptype='Universal'
		    $dsgrp_groups[$grouptype]['dsgrp_totalcnt']++
		    if($total.ManagedBy -eq "" -or $total.ManagedBy -eq $Null )
		    {
		        Write-Host $grouptype 'dsgrp_orphndgrp#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberscount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		        $dsgrp_groups[$grouptype]['dsgrp_ownlesscnt']++
		    }
		    if ($total.WhenChangedUTC -ne "" -and [DateTime]($total.WhenChangedUTC) -gt $LastMsmtTime)  
		    {
		        Write-Host $grouptype 'dsgrp_changedutc#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberscount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		        $dsgrp_groups[$grouptype]['dsgrp_changedcnt']++
		    }

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

		    if ($total.GroupMemberscount -eq 0)
		    {
		        Write-Host $grouptype 'dsgrp_emptygrp#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' '-5' '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		        $dsgrp_groups[$grouptype]['dsgrp_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{
            $exp=$_.Exception.Message
            Write-Error 'error occures while changing data format in 2nd loop' $exp 
        }
        $grouptype=($total2.GroupType).Trim()
        $intialgrptype=$grouptype
	    if($grouptype.StartsWith('Universal,'))
	    {

		$grouptype=$grouptype.Substring(('Universal,'.Length)).Trim()
	    }

		$status=$total2.isvalids
		if($status -eq 'True')
		{
			$status='Active'
		}
		else
		{
			$status='Inactive'
		}        


        $smtpadrs=$total2.PrimarySmtpAddress
        $bolean=$false
        foreach($total in $disbtedgrp)
	    {
        
            if($smtpadrs -eq $total.PrimarySmtpAddress)
            {
                $bolean=$true
	        }
        }

        if($recipnt2 -ne "" -and $recipnt2 -ne $null -and $bolean -eq $false)
        {
		    Write-Host $grouptype 'dsgrp_softdetedgrp#'$total2.DisplayName'~!~'$total2.PrimarySmtpAddress'~!~'$total2.Alias'~!~'$status'~!~' $total2.GroupMemberscount '~!~'$total2.WhenChangedUTC'~!~'$total2.WhenCreatedUTC           
		    $dsgrp_groups[$grouptype]['dsgrp_softdetedcnt']++

            if($intialgrptype.StartsWith('Universal,'))
            {
              $grouptype='Universal'
              Write-Host $grouptype 'dsgrp_softdetedgrp#'$total2.DisplayName'~!~'$total2.PrimarySmtpAddress'~!~'$total2.Alias'~!~'$status'~!~' $total2.GroupMemberscount '~!~'$total2.WhenChangedUTC'~!~'$total2.WhenCreatedUTC           
		      $dsgrp_groups[$grouptype]['dsgrp_softdetedcnt']++
  
            }
	    }
       }
     }



	foreach($grup  in $dsgrp_groups.Keys)
	{
	    foreach($key in $dsgrp_groups[$grup].Keys)
	    {
		Write-Host $grup$key  $dsgrp_groups[$grup][$key]
	    }
	}