##/*****************************************************************************
##Author                :               Guravareddy.T
##Purpose               :               O365 Gropus Types 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 "unifiedgroups" -keyFileName "kunifiedgroups" -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 'unifiedgroups' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kunifiedgroups' -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='unifiedgroups'.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()
	$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]['changedcnt'] = 0
		$dsgrp_groups[$grouptype]['createdcnt'] = 0
		$dsgrp_groups[$grouptype]['softdeletcnt'] = 0
		$dsgrp_groups[$grouptype]['totalcnt'] = 0
		$dsgrp_groups[$grouptype]['publiccnt'] = 0
		$dsgrp_groups[$grouptype]['privatecnt'] = 0
		$dsgrp_groups[$grouptype]['orphancnt'] = 0
		$dsgrp_groups[$grouptype]['emptycnt'] = 0
		$dsgrp_groups[$grouptype]['groupextmemcnt'] = 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' $exp  
            }
	    $grouptype=($total.GroupType).Trim()
	    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'
		}

	        if($total.WhenSoftDeleted -eq "" -or $total.WhenSoftDeleted -eq $null)
                {
			$dsgrp_groups[$grouptype]['totalcnt']++
                }
	     
		 if($total.AccessType -eq "Public")
		 {
		      Write-Host $grouptype 'publiccnt#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberCount '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		      $dsgrp_groups[$grouptype]['publiccnt']++
		 } 

		 if($total.AccessType -eq "Private") 
		 { 
		     Write-Host $grouptype 'privatecnt#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberCount'~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		     $dsgrp_groups[$grouptype]['privatecnt']++
		 }

		if($total.ManagedBy -eq "" -or $total.ManagedBy -eq $Null ) 
		{
		    Write-Host $grouptype 'orphancnt#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberCount'~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		    $dsgrp_groups[$grouptype]['orphancnt']++
		}
		if($total.GroupMemberCount -eq  0) 
		{
		    Write-Host $grouptype 'emptycnt#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' '-5' '~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		    $dsgrp_groups[$grouptype]['emptycnt']++
		}
		if($total.GroupExternalMemberCount -gt 0) 
		{
		    Write-Host $grouptype 'groupextmemcnt#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupExternalMemberCount'~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		    $dsgrp_groups[$grouptype]['groupextmemcnt']++
		}
		if ($total.WhenSoftDeleted -ne "" -and  [DateTime]($total.WhenSoftDeleted) -gt $LastMsmtTime)  {
		    Write-Host $grouptype 'softdeletcnt#'$total.DisplayName'~!~'$total.PrimarySmtpAddress'~!~'$total.Alias'~!~'$status'~!~' $total.GroupMemberCount'~!~'$total.WhenChangedUTC'~!~'$total.WhenCreatedUTC
		    $dsgrp_groups[$grouptype]['softdeletcnt']++
		}

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

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

	}

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