clear
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value
$egurkhaPath=$egInstallpath.Value.ToString()
$egEncryPath=$egurkhaPath+"\lib\EGFileEncryption.psm1"
$egDatnKy=$egurkhaPath+'\lib\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]
$DateProxyhostRepName=($TestInputs[4]).ToString().Split("#")
$readeddate=[datetime]($DateProxyhostRepName[0].Trim())
$proxyserverip=($DateProxyhostRepName[1]).ToString().trim()
$reportingname=($DateProxyhostRepName[2]).ToString().trim()


$ToReadDate=$readeddate.tostring(“yyyy-MM-dd”)
$proxyserver='http://'+$proxyserverip
$domain=Eg-GetDomain -userName $userName -Password $Password -proxyUsr $proxyUsr -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver



$rptPath=$egurkhaPath+'\agent\O365\'+$reportingname
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

try{
    $msGraphPath=$egurkhaPath+"\agent\O365\MsGraph"
    $keyFileNam = '\GraphDetailsKey.dat'
    $unProtPath= $msGraphPath+'\GraphDetails.dat'
    $kvalue= Get-Content -Path $msGraphPath$keyFileNam
    $null=Unprotect-File $unProtPath -Algorithm AES -KeyAsPlainText $kvalue -DstSuffix '.txt'
    $SkypeInput=$msGraphPath+"\GraphDetails.txt"
    $GetInput = Get-Content -Path $SkypeInput
}catch{
    Write-Error -Message "File not found. The $GetInput location does not contain GraphDetails "
}



Function Eg-InvokeUrl(){
	[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=1)]
        [String]$Url, 
        [Parameter(Mandatory=$true, Position=2)]
        [String]$filePath,
        [Parameter(Mandatory=$true, Position=3)]
        [Object]$header               
    )

    Process
    {
        $query = Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url
        $query=$query.Replace('ï»¿','')
        $query=$query.Replace(' ','')
        $resultarray = ConvertFrom-Csv -InputObject $query
        $reprts=$resultarray | ConvertTo-Json 
        $jsonreprt=@()
        $jsonreprt='{ "Usage" :['+$reprts+']}'
        $reports=$jsonreprt | ConvertFrom-Json
        for($i=0;$i -lt $reports.Usage.Length ;$i++ ){  
            $reports.Usage[$i] |Export-Csv $filePath -Append -NoTypeInformation -Force
        }
    }
}


$flag=$false
foreach($inp in $GetInput){
    if($inp.StartsWith('[') -and $inp.Contains($domain)){
        $flag=$true
    }
    if($flag){
        if($inp.Contains("client_id")){
            $appId =$inp.ToString().Substring($inp.IndexOf('~')+1)
        }
        if($inp.Contains("client_secret")){
            $appSecret =$inp.ToString().Substring($inp.IndexOf('~')+1)
        }
        if($inp.Contains("TenantName")){
            $tenantID=$inp.ToString().Substring($inp.IndexOf('~')+1)
        }
        if($inp.Contains("Authority")){
            $authString = $inp.ToString().Substring($inp.IndexOf('~')+1)
            $authString=$authString+$domain
        }
        if($inp.Contains("Resource")){
            $Resource =$inp.ToString().Substring($inp.IndexOf('~')+1)
            $flag=$false
        }
    }
}

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

$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $appId, $appSecret
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authString
$context = $authContext.AcquireTokenAsync($Resource, $creds).Result
$authCode=$context.CreateAuthorizationHeader()
$header = @{
    'Authorization'=$authCode
}


$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$O365GrupsActvts = $rptPath+'\getOffice365GroupsActivityDetail'+$timenow+'.csv'
#$date=([Datetime]"2019-02-21").tostring(“yyyy-MM-dd”)
$O365GrupsActvtUrl ="https://graph.microsoft.com/v1.0/reports/getOffice365GroupsActivityDetail(period='D7')"   #date="+$date+")"
Eg-InvokeUrl -Url $O365GrupsActvtUrl -filePath $O365GrupsActvts -header $header

$GrpsAct= Import-Csv  $O365GrupsActvts | Select * |  Where-Object { $_.IsDeleted -eq 'FALSE'}
$csvDir=$rptPath+'/'
Eg-DeleteCsvFiles -FilePath $csvDir -Pattern 'getOffice365GroupsActivityDetail'
$reportdate=$GrpsAct | select ReportRefreshDate -First 1
$reportdate=($reportdate.ReportRefreshDate)
if([datetime]$reportdate -ge [datetime]$ToReadDate)
{
    Write-Host 'ReadedDate for the Date#'$reportdate
} 
else{ 
    Write-Host 'thereIs No Data on#'$ToReadDate
    exit  
    }



$totalgrpscnt=$GrpsAct.Count
Write-Host '***********************Start****************************'
<#
if($totalgrpscnt){

    $topGrups = $GrpsAct | select * | Sort-Object { $_.MemberCount -as [int] }  -Descending | select  -First 5
    foreach($in in $topGrups)
    {

        Write-Host 'topGrpsMembersCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.MemberCount

    }
}

Write-Host '***************************************************'

$sumofExternalMembCnt= ($GrpsAct | select ExternalMemberCount | measure-object -property ExternalMemberCount -Sum).sum
if($sumofExternalMembCnt){

    $topExternalMembCnt= $GrpsAct | select * | Sort-Object { $_.ExternalMemberCount -as [int] }  -Descending  | select -First 5
    foreach($in in $topExternalMembCnt)
    {

        Write-Host 'topGrpsExternalMembersCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.ExternalMemberCount

    }

}
#>
Write-Host '***************************************************'

$sumofExMailBoxStorage= ($GrpsAct | select 'ExchangeMailboxStorageUsed(Byte)' | measure-object -property 'ExchangeMailboxStorageUsed(Byte)' -Sum).sum
if($sumofExMailBoxStorage){

    $sumofExMailBoxStorage = [math]::round($sumofExMailBoxStorage/1Gb, 2) 
    $topExMailBoxByStorage= $GrpsAct | select * | Sort-Object { $_.'ExchangeMailboxStorageUsed(Byte)' -as [double] }  -Descending| select -First 10
    foreach($in in $topExMailBoxByStorage)
    {
        $exchangembUsed = [math]::round(($in.'ExchangeMailboxStorageUsed(Byte)')/1Mb,2)
        Write-Host 'topGrpsWithExchngMailBoxStorageUsage#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $exchangembUsed

    }
}

Write-Host '***************************************************'

$sumofExMailBoxItemsCnt= ($GrpsAct | select ExchangeMailboxTotalItemCount | measure-object -property ExchangeMailboxTotalItemCount -Sum).sum
if($sumofExMailBoxItemsCnt){
    
    $topExMailBoxByItemsCnt= $GrpsAct | select * | Sort-Object { $_.ExchangeMailboxTotalItemCount -as [double] }  -Descending | select -First 10
    foreach($in in $topExMailBoxByItemsCnt)
    {

        Write-Host 'topGrpsExchangeMailboxTotalItemCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.ExchangeMailboxTotalItemCount

    }
}

Write-Host '***************************************************'

$sumofSharepointTotlfilsCnt= ($GrpsAct | select SharePointTotalFileCount | measure-object -property SharePointTotalFileCount -Sum).sum
if($sumofSharepointTotlfilsCnt){
    
    $topSharepointTotlfilsCnt= $GrpsAct | select * | Sort-Object { $_.SharePointTotalFileCount -as [double] }  -Descending | select -First 10
    foreach($in in $topSharepointTotlfilsCnt)
    {

        Write-Host 'topGrpsSharepointToalFileCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.SharePointTotalFileCount

    }
}

Write-Host '***************************************************'

$sumofSharepointStageUsed= ($GrpsAct | select 'SharePointSiteStorageUsed(Byte)' | measure-object -property 'SharePointSiteStorageUsed(Byte)' -Sum).sum
if($sumofSharepointStageUsed){

    $sumofSharepointStageUsed = [math]::round($sumofSharepointStageUsed/1Gb, 2) 
    $topSharepointStageUsed= $GrpsAct | select * | Sort-Object { $_.'SharePointSiteStorageUsed(Byte)' -as [double] }  -Descending | select -First 10
    foreach($in in $topSharepointStageUsed)
    {
        $SharepointsiteUsed = [math]::round(($in.'SharePointSiteStorageUsed(Byte)')/1Mb,2)
        Write-Host 'topGrpsSharePointSiteStorageUsed#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $SharepointsiteUsed

    }
}
Write-Host '***************************************************'

$sumofSharepointActfilesCnt= ($GrpsAct | select SharePointActiveFileCount | measure-object -property SharePointActiveFileCount -Sum).sum
if($sumofSharepointActfilesCnt){

    $topSharepointActfilesCnt= $GrpsAct | select * | Sort-Object { $_.SharePointActiveFileCount -as [double] } -Descending | select -First 10
    foreach($in in $topSharepointActfilesCnt)
    {

        Write-Host 'topGrpsSharePointActiveFileCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.SharePointActiveFileCount

    }
}

Write-Host '***************************************************'

$sumofExcngRcvdEmailsCnt= ($GrpsAct | select ExchangeReceivedEmailCount | measure-object -property ExchangeReceivedEmailCount -Sum).sum
if($sumofExcngRcvdEmailsCnt){

    $topExcngRcvdEmailsCnt= $GrpsAct | select * | Sort-Object  { $_.ExchangeReceivedEmailCount -as [double] } -Descending | select -First 10
    foreach($in in $topExcngRcvdEmailsCnt)
    {

    Write-Host 'topGrpsExchangeReceivedEmailCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.ExchangeReceivedEmailCount

    }
}

Write-Host '***************************************************'

$sumofYamerPstedMsgCnt= ($GrpsAct | select YammerPostedMessageCount | measure-object -property YammerPostedMessageCount -Sum).sum
if($sumofYamerPstedMsgCnt){

    $topYamerPstedMsgCnt= $GrpsAct | select * | Sort-Object { $_.YammerPostedMessageCount -as [double] } -Descending | select -First 10
    foreach($in in $topYamerPstedMsgCnt)
    {
        Write-Host 'topGrpsYammerPostedMessageCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.YammerPostedMessageCount
    }
}

Write-Host '***************************************************'

$sumYamerReadMsgCnt= ($GrpsAct | select YammerReadMessageCount | measure-object -property YammerReadMessageCount -Sum).sum
if($sumYamerReadMsgCnt){

    $topYammerReadMsgCnt= $GrpsAct | select * | Sort-Object { $_.YammerReadMessageCount -as [double] } -Descending | select -First 10
    foreach($in in $topYammerReadMsgCnt)
    {
        Write-Host 'topGrpsYammerReadMessageCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.YammerReadMessageCount
    }
}

Write-Host '***************************************************'

$sumYamerLikedMsgCnt= ($GrpsAct | select YammerLikedMessageCount | measure-object -property YammerLikedMessageCount -Sum).sum
if($sumYamerLikedMsgCnt){
 
    $topYamerLikedMsgCnt= $GrpsAct | select * | Sort-Object { $_.YammerLikedMessageCount -as [double] } -Descending | select -First 10
    foreach($in in $topYamerLikedMsgCnt)
    {
        Write-Host 'topGrpsYammerLikedMessageCount#' $in.GroupDisplayName ~!~ $in.OwnerPrincipalName ~!~ $in.LastActivityDate ~!~ $in.GroupType ~!~ $in.YammerLikedMessageCount
    }
}

Write-Host 'measures#' $sumofExMailBoxStorage ~ $sumofExMailBoxItemsCnt ~ $sumofSharepointTotlfilsCnt ~ $sumofSharepointStageUsed ~ $sumofSharepointActfilesCnt ~ $sumofExcngRcvdEmailsCnt ~ $sumofYamerPstedMsgCnt ~ $sumYamerReadMsgCnt ~ $sumYamerLikedMsgCnt

Write-Host '*************************Done**************************'





