<#
    /*****************************************************************************
    Author            :       Mounika Kuna
    Purpose           :       Provides Office 365 Groups Activity Details
    Created           :       18/07/2020    
    /*****************************************************************************
#>

$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
$PSDefaultParameterValues = @{'*:Encoding' = 'utf8'}

clear
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egurkhaPath=($scriptPath.Substring(0,$scriptPath.ToLower().IndexOf('egurkha')+7)).Trim()
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy -WarningAction SilentlyContinue

#<#
$TestInputs=$args
$username=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUser=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$proxyserver=$TestInputs[4]
$readingdate=[datetime]$TestInputs[5]
$rptNam=$TestInputs[6]
$graphDetails=$TestInputs[7]
if($graphDetails -and $graphDetails -ne 'none'){
    $graphDetailsArr=($graphDetails).ToString() -Split ("~!~")
    $appId=$graphDetailsArr[0]
    $appSecret=$graphDetailsArr[1]
    $authString=$graphDetailsArr[2]
    $resource=$graphDetailsArr[3]
}
#>

$langPath=$egurkhaPath+'\agent\config\O365_lang.ini'
$encTyp=Eg-GetINIContent -Path $langPath -Subject 'File_Type' -Key 'encoding'

if($proxyUser.toString().toLower().Trim() -eq 'none') { $proxyUser=$proxyUser.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserver.toString().toLower().Trim().Contains('none')) { $proxyserver=$proxyserver.toString().toLower().Trim() }
if(!$proxyserver.ToString().ToLower().Contains('none')){
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUser.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUser, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
}

$toReadDat=$readingdate.tostring(“yyyy-MM-dd”)
$rptPath=$egurkhaPath+'\agent\EXO\'+$rptNam
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

$typePath=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
Add-Type -Path $typePath

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$O365GrpsActDtlsCSV=$rptPath+'\O365GrpsActDtls'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $O365GrpsActDtlsCSV
$url = "https://graph.microsoft.com/v1.0/reports/getOffice365GroupsActivityDetail(period='D7')"
while($true){
    Eg-InvokeGraphUrl -Url $url -filePath $O365GrpsActDtlsCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource
    $TotalO365GrpsActDtls=Import-Csv $O365GrpsActDtlsCSV -Encoding $encTyp
    $url=$TotalO365GrpsActDtls.'@odata.nextLink'
    if($url -eq $null -or $url -eq ''){
        break
    }
}
$diffence=(NEW-TIMESPAN –Start $readingdate –End (Get-Date) | Select-Object Days).Days
[System.GC]::GetTotalMemory($true) | out-null
$notFirsttime = $false
while($diffence -ge 1)
{
    if($notFirsttime){ $readingdate=$readingdate.AddDays(1) }
    $actualdate=$readingdate
    $notFirsttime = $true
    $TotalO365GrpsAct =$TotalO365GrpsActDtls | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
    if($TotalO365GrpsAct)
    {
        Write-Host 'ReadDate for the Date#'$actualdate.tostring(“yyyy-MM-dd”)
        break
    }
    else
    {
        Write-Host 'thereIs No Data on#'$actualdate.tostring(“yyyy-MM-dd”)
    }
    $diffence=$diffence-1
}
[System.GC]::GetTotalMemory($true) | out-null
try{
    foreach($O365GrpsActvty in $TotalO365GrpsAct){
        if($O365GrpsActvty.MemberCount -eq ""){ $MemberCount='0'}
            else{ 
                $MemberCount=$O365GrpsActvty.MemberCount
                    if($MemberCount -ne '0'){
                        $MemberCountDD=$O365GrpsActvty.ReportRefreshDate+'~!~'+$O365GrpsActvty.GroupDisplayName+'~!~'+$O365GrpsActvty.OwnerPrincipalName+'~!~'+$O365GrpsActvty.LastActivityDate+'~!~'+$O365GrpsActvty.GroupType+'~!~'+$O365GrpsActvty.GroupId
                        Write-Host 'MemberCountDD='$MemberCountDD
                    }
            }
        if($O365GrpsActvty.ExternalMemberCount -eq ""){ $ExternalMemberCount='0'}
            else{ $ExternalMemberCount=$O365GrpsActvty.ExternalMemberCount}
        if($O365GrpsActvty.ExchangeReceivedEmailCount -eq ""){ $ExchangeReceivedEmailCount='0'}
            else{ $ExchangeReceivedEmailCount=$O365GrpsActvty.ExchangeReceivedEmailCount}
        if($O365GrpsActvty.SharePointActiveFileCount -eq ""){ $SharePointActiveFileCount='0'}
            else{ $SharePointActiveFileCount=$O365GrpsActvty.SharePointActiveFileCount}
        if($O365GrpsActvty.YammerPostedMessageCount -eq ""){ $YammerPostedMessageCount='0'}
            else{ $YammerPostedMessageCount=$O365GrpsActvty.YammerPostedMessageCount}
        if($O365GrpsActvty.YammerReadMessageCount -eq ""){ $YammerReadMessageCount='0'}
            else{ $YammerReadMessageCount=$O365GrpsActvty.YammerReadMessageCount}
        if($O365GrpsActvty.YammerLikedMessageCount -eq ""){ $YammerLikedMessageCount='0'}
            else{ $YammerLikedMessageCount=$O365GrpsActvty.YammerLikedMessageCount}
        if($O365GrpsActvty.ExchangeMailboxTotalItemCount -eq ""){ $ExchangeMailboxTotalItemCount='0'}
            else{ $ExchangeMailboxTotalItemCount=$O365GrpsActvty.ExchangeMailboxTotalItemCount}  
        if($O365GrpsActvty.SharePointTotalFileCount -eq ""){ $SharePointTotalFileCount='0'}
            else{ $SharePointTotalFileCount=$O365GrpsActvty.SharePointTotalFileCount}    
    $Output = $O365GrpsActvty.GroupDisplayName+'~'+$MemberCount+'~'+$ExternalMemberCount+'~'+$ExchangeReceivedEmailCount+'~'+$SharePointActiveFileCount+'~'+$YammerPostedMessageCount+'~'+$YammerReadMessageCount+'~'+$YammerLikedMessageCount+'~'+$ExchangeMailboxTotalItemCount+'~'+[math]::Round(($O365GrpsActvty.ExchangeMailboxStorageUsed/1073741824),2)+'~'+$SharePointTotalFileCount+'~'+[math]::Round(($O365GrpsActvty.SharePointSiteStorageUsed/1073741824),2)
    Write-Host 'info&Measures='$Output	
    }
}catch{    
    $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	Write-error "Error Occured in O365GrpsActDtlsTest Script >>> "$exceptionmsg 
}
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($O365GrpsActDtlsCSV) -eq 'True'){
    Remove-Item $O365GrpsActDtlsCSV
}
