##/******************************************************************************************
##Author                :     Guravareddy T
##Purpose               :     Display the O365 Security Groups
##Created               :     06/21/2018

clear
[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]
$repotingnamendfrq=$TestInputs[4]
$rptndfrqcy=$repotingnamendfrq.split('#')
$reportingName=$rptndfrqcy[0]
$frequency=$rptndfrqcy[1]
$proxyserverip=($rptndfrqcy[2]).ToString().trim()
$rptPath='O365/'+$reportingName
$azureVal=Eg-GetAzureEnv -UserName $userName
$azureEnvArr=$azureVal.Split(',')
if($proxyUsr.toString().toLower().Trim() -eq 'none') { $proxyUsr=$proxyUsr.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserverip.toString().toLower().Trim().Contains('none')) { $proxyserverip=$proxyserverip.toString().toLower().Trim() }


$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
#[System.Net.CredentialCache]::DefaultCredentials=$cred
if(!$proxyserverip.Contains('none')){
    $proxyserver='http://'+$proxyserverip
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUsr -ne 'none' -and $proxyPass -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred   #[System.Net.CredentialCache]::DefaultNetworkCredentials
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
 }
Connect-MsolService -Credential $cred -AzureEnvironment $azureEnvArr[0]

$null=Connect-AzureAD -Credential $cred -AzureEnvironmentName $azureEnvArr[0]
$totalcnt=0
$emptygrps=0
$orphnedgrps=0
$newgrupscnt=0
$softdeletcnt=0

    #---------------START CMDLET------------------
    Try{
        $writArr = Eg-WriteFile -ComntRptPath $rptPath -FileName "O365secugrp" -keyFileName "kO365secugrp" -EgPath $egurkhaPath
        Get-AzureADMSGroup | Select-Object * | where-Object { $_.Mail -eq $null}|Export-Csv $writArr[1]
        $null=Protect-File  $writArr[1] -Algorithm AES -KeyAsPlainText $writArr[0] -RemoveSource
    }Catch{
    $exception=$_.Exception
     Write-Error -Message " The exception while writting data to file $exception " 
    }
    try{
    $readfiles=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365secugrp" -keyFileName "kO365secugrp" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $sectygrps= import-csv $csvfile
    Remove-Item $csvfile
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'O365secugrp' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kO365secugrp' -InputFile $readfiles[4]
    Write-Host "ReadFile:"$readfiles[3]
    }catch{
    $exception=$_.Exception
     Write-Error -Message "File not found. The $reportingname location does not contain Security group files. $exception " 
     }

#Get-AzureADMSDeletedGroup | Sort-Object DisplayName| Format-Table Id, DisplayName, Description, Visibility
#$sectygrps=Get-AzureADMSGroup | Select-Object * | where-Object { $_.Mail -eq $null} 

#Get-AzureADGroup| Select-Object * | where-Object { $_.Mail -eq $null} 
$startdate=(Get-Date).ToUniversalTime()
$CultureDateTimeFormat = (Get-Culture).DateTimeFormat
$DateFormat = $CultureDateTimeFormat.ShortDatePattern
$TimeFormat = $CultureDateTimeFormat.LongTimePattern
$DateTimeFormat = "$DateFormat $TimeFormat"
foreach($grp in $sectygrps)
{
    $totalcnt++
    $mebers=Get-MsolGroupMember -GroupObjectId $grp.Id | Select-Object displayname

    $owner=Get-AzureADGroupOwner -ObjectId $grp.Id | Select-Object displayname
    #$cretntime=$grp.CreatedDateTime
    $grp.CreatedDateTime=$grp.CreatedDateTime.Replace('??','')
    $cretntime=[DateTime]::ParseExact(($grp.CreatedDateTime),$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)

    try{
        $mebcnt=$mebers.count
    }catch{$mebcnt=0}
    
    if($mebcnt -eq 0 -or $mebcnt -eq $null -or $mebcnt -eq " "){
        $emptygrps++
        Write-Host '##ddEmpty Groups'$grp.DisplayName '~!~' -5
    }
    if(!$owner)
    {
        write-host '>>>>>>'$owner
        $orphnedgrps++
        Write-Host '##ddOrphaned Groups'$grp.DisplayName '~!~' $mebcnt

    }
    write-host $cretntime  '>>' $startdate
    if([DateTime]$cretntime -ge [DateTime]$startdate){
   write-host $cretntime  '>>' $startdate
        $newgrupscnt++
        Write-Host '##ddcreated Groups'$grp.DisplayName '~!~' $mebcnt

    }

    write-host '##ddTotals'$grp.DisplayName '~!~' $mebcnt
}



    try{
    $filepath=$egurkhaPath+'/agent/'+$rptPath+'/'
	$fileread2=Get-ChildItem -Path $filepath |Where-Object {$_.Name -like 'O365secugrp*.dat'}| Sort-Object LastWriteTime -Descending | Select-Object -index 1|Select Name
	$filepath2=$filepath+$fileread2.Name
	$datpos = $fileread2.name.IndexOf(".dat")
	$length='O365secugrp'.Length
	$tmpvalue = $fileread2.name.toString().substring($length,($datpos-$length)) 
	$kfileval2 = "kO365secugrp"+$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	
	$securitygrp2= import-csv $recpFile2
	Remove-Item $recpFile2

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

    if($securitygrp2 -ne "" -and $securitygrp2 -ne $null){
      foreach($total2 in $securitygrp2)
      {
        $mebcnt=0
        $displayname=$total2.DisplayName
        $bolean=$false
        foreach($total in $sectygrps)
	    {
            $mebers=Get-MsolGroupMember -GroupObjectId $grp.Id | Select-Object displayname
            $cretntime=$grp.CreatedDateTime
            try{
                $mebcnt=$mebers.count
            }catch{$mebcnt=0}
            if($displayname -eq $total.DisplayName)
            {
                $bolean=$true
	        }
        }

        if($securitygrp2 -ne "" -and $securitygrp2 -ne $null -and $bolean -eq $false)
        {
            Write-Host '##ddsoftdeleted'$total2.DisplayName'~!~'$mebcnt
	       $softdeletcnt++
	    }
       }
     }

write-host '##Totalgrps'$totalcnt
Write-Host '##orphnedgrps'$orphnedgrps
Write-Host '##emptygrps'$emptygrps
Write-Host '##createdgrps'$newgrupscnt
Write-Host '##softdeletedgrps'$softdeletcnt
