$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
Import-Module MsOnline -ea 0 -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]
$strgLimit=$TestInputs[5]
$readDat=[DateTime]$TestInputs[6]
$rptNam=$TestInputs[7]
$inactvDays=[int]$TestInputs[8]
$topnddNTestFreq=($TestInputs[9]).ToString().Split("#")
$rptTopNDD=[int]$topnddNTestFreq[0]
$testFrequency=[int]$topnddNTestFreq[1]
$o365_domain=$TestInputs[10]
$graphDetails=$TestInputs[11]
$appDetails=$TestInputs[12]

if($graphDetails -and $graphDetails -ne 'none'){
    $graphDetailsArr=($graphDetails).ToString() -Split ("~!~")
    $appId=$graphDetailsArr[0]
    $appSecret=$graphDetailsArr[1]
    $authString=$graphDetailsArr[2]
    $resource=$graphDetailsArr[3]
}

if($appDetails -and $appDetails -ne 'none'){
    $appDetailsArr=($appDetails).ToString() -Split ("~!~")
    $clientId=$appDetailsArr[0]
    $tenantName=$appDetailsArr[1]
    $thumbPrint=$appDetailsArr[2]
}
#>

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

$rptPath=$egurkhaPath+'\agent\ODB\'+$rptNam
if(!(Test-Path -Path $rptPath )){
    $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}
$logPath=$rptPath+'\ODBSiteUsageDtls.log'
$isWriteLog=$false

$url = 'https://'+$o365_domain+'-admin.sharepoint.com'
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=$readDat.tostring(“yyyy-MM-dd”)

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

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

    Process
    {
        $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
        }
        $query = [System.Text.Encoding]::$encTyp.GetString((Invoke-WebRequest -Method $Method -Headers $header -Uri $Url -UseBasicParsing).RawContentStream.ToArray())
        #$query = Invoke-RestMethod -Method $Method -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
        $psobje=''
        for($i=0;$i -lt $reports.Usage.Length ;$i++ ){   
           $reports.Usage[$i] |Sort-Object -Property $PropsVal -Descending |Export-Csv $filePath -Encoding $encTyp -Append -NoTypeInformation -Force
        }
    }
}

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$ODBUsageAccDtls=$rptPath+'\ODBSitUsageAccDtls'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $ODBUsageAccDtls
$ODBUsageAccCnts=$rptPath+'\ODBSitUsageAccCnts'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $ODBUsageAccCnts

$url1="https://graph.microsoft.com/v1.0/reports/getOneDriveUsageAccountDetail(period='D7')"
$url2="https://graph.microsoft.com/v1.0/reports/getOneDriveUsageAccountCounts(period='D7')"
Try{
    Eg-InvokeUrl -Url $url1 -Method 'Get' -PropsVal 'ReportDate' -filePath $ODBUsageAccDtls
    Eg-InvokeUrl -Url $url2 -Method 'Get' -PropsVal 'ReportDate' -filePath $ODBUsageAccCnts

    $usagAccDtlArr=Import-Csv $ODBUsageAccDtls -Encoding $encTyp
    $usagAccCntsArr=Import-Csv $ODBUsageAccCnts -Encoding $encTyp

    $accDtlsRptDat=$usagAccDtlArr | select ReportRefreshDate -First 1
    $accDtlsRptDat=($accDtlsRptDat.ReportRefreshDate)

    if([datetime]$accDtlsRptDat -ge [datetime]$toReadDat){
        Write-Host 'ReadedDate for the Date#'$accDtlsRptDat
        $ldate=($usagAccDtlArr |sort -Property LastActivityDate -Descending |Select-Object -First 1).LastActivityDate

        $timenow = [int][double]::Parse((Get-Date -UFormat %s))
        $SPOSiteDtls=$rptPath+'\ODBSPOSiteDtls'+$timenow+'.csv'
        Eg-RemoveGraphcsvFiles -rmvPath $SPOSiteDtls
        $MsolUsrDtls=$rptPath+'\ODBMsolUsrDtls'+$timenow+'.csv'
        Eg-RemoveGraphcsvFiles -rmvPath $MsolUsrDtls

		# ****ORPHANED SITES*****

        Eg-WriteLog -writString ('Entering ORPHANED SITES ....') -LogPath $logPath -ReportingName $rptNam -TestFreq $testFrequency -isWriteLog $isWriteLog
        $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $password -asplaintext -force)  
        if($appDetails -and $appDetails -ne 'none'){
            $null=Connect-AzureAD -CertificateThumbprint $thumbPrint -ApplicationId $clientId -TenantId $tenantName
        }else{
            Connect-MsolService -Credential $cred
        }
        Try{
            if($appDetails -and $appDetails -ne 'none'){
                Get-AzureADUser -All $True | Where-Object{$_.UserType -eq 'Member'} |Export-Csv $MsolUsrDtls -Encoding $encTyp -Append -NoTypeInformation -Force
	        }else{
                Get-MsolUser -All | Where-Object{$_.UserType -eq 'Member'} |Export-Csv $MsolUsrDtls -Encoding $encTyp -Append -NoTypeInformation -Force
            }
        }Catch{
            Eg-WriteLog -writString ('[ODBSiteUsageDtls] Exception occurred in Get MsolUser...'+$_.Exception.Message) -LogPath $logPath -ReportingName $rptNam -TestFreq $testFrequency -isWriteLog $isWriteLog
        }

        if($appDetails -and $appDetails -ne 'none'){
		    Connect-PnPOnline -url $url -clientId $clientId -Tenant $tenantName -Thumbprint $thumbPrint
        }else{
            Connect-SPOService -Url $url -Credential $cred
        }
        Try{
            if($appDetails -and $appDetails -ne 'none'){
                Get-PnPTenantSite -IncludeOneDriveSites -Filter "Url -like '-my.sharepoint.com/personal/'"|select url,Owner | Export-Csv $SPOSiteDtls -Encoding $encTyp -Append -NoTypeInformation -Force
            }else{
                Get-SPOSite -IncludePersonalSite $true -Limit all -Filter "Url -like '-my.sharepoint.com/personal/'"|select url,Owner | Export-Csv $SPOSiteDtls -Encoding $encTyp -Append -NoTypeInformation -Force
            }
        }
        Catch{
            Eg-WriteLog -writString ('[ODBSiteUsageDtls] Exception occurred in Get SPOSite...'+$_.Exception.Message) -LogPath $logPath -ReportingName $rptNam -TestFreq $testFrequency -isWriteLog $isWriteLog
        }
        Eg-WriteLog -writString ('[ODBSiteUsageDtls] After Get SPOSite...') -LogPath $logPath -ReportingName $rptNam -TestFreq $testFrequency -isWriteLog $isWriteLog
        [System.GC]::GetTotalMemory($true) | out-null

        $SPOSiteDtlArr=Import-Csv $SPOSiteDtls -Encoding $encTyp
        $MsolUsrDtlArr=Import-Csv $MsolUsrDtls -Encoding $encTyp

        $orphCnt=0
        Eg-WriteLog -writString ('[ODBSiteUsageDtls] MsolUsrDtlArr UserPrincipalName -->> '+$MsolUsrDtlArr.UserPrincipalName) -LogPath $logPath -ReportingName $rptNam -TestFreq $testFrequency -isWriteLog $isWriteLog 
        foreach($sitDtl in $SPOSiteDtlArr){
            if($MsolUsrDtlArr.UserPrincipalName -notcontains $sitDtl.Owner){
                $orphanDD='OrphanedSites~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+$sitDtl.Url
                Eg-WriteLog -writString ('[ODBSiteUsageDtls] orphanDD -->> '+$orphanDD) -LogPath $logPath -ReportingName $rptNam -TestFreq $testFrequency -isWriteLog $isWriteLog
                if($orphCnt -lt 50){
                    Write-Host $orphanDD
                }
                $orphCnt++
            }
        }
        if($orphCnt -eq 0){
            $orphCnt=-5
        }
        Eg-WriteLog -writString ('[ODBSiteUsageDtls] Orphaned sites count -->> '+$orphCnt) -LogPath $logPath -ReportingName $rptNam -TestFreq $testFrequency -isWriteLog $isWriteLog
	    [System.GC]::GetTotalMemory($true) | out-null

        # *************ORPHANED SITES - END**********

        $totalSites=0
        $activSites=0
        $usagAccCntsArr|foreach{if($_.ReportDate -eq $ldate){$totalSites=[int]$_.Total;$activSites=[int]$_.Active}}
        if($activSites -ge 0){$activSites=$activSites}else{$activSites=0}
        if($totalSites -ge 0){$totalSites=$totalSites}else{$totalSites=0}
        if($totalSites -gt 0){$activSitesPercent=[math]::Round((($activSites/$totalSites)*100),2)}else{$activSitesPercent=0}        

        $currDat=[DateTime](Get-Date)
        $chkDate=$currDat.AddDays(-$inactvDays)
        $toChkDat=$chkDate.tostring(“yyyy-MM-dd”)
        $inActivSites=0
        $sortInActvSitDtl=@()
        $usagAccDtlArr | foreach{if($_.IsDeleted -eq 'FALSE' -and $_.LastActivityDate -ne ""){if([datetime]$_.LastActivityDate -lt [datetime]$toChkDat){$inActivSites++;$sortInActvSitDtl+=$_}}}
        $sortInActvSitDtl|Sort-Object {$_.LastActivityDate -as [DateTime]} -Descending | Select-Object -First $rptTopNDD |foreach{
        $StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5)        
        $StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)
        if([long]$_."StorageUsed(Byte)" -ge 0){$StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5) }else{$StgUsd=0}        
        if([long]$_."StorageAllocated(Byte)" -ge 0){$StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)}else{$StgAllctd=0}
        $inActvSitesDD='InactiveSitesDD~'+$_.LastActivityDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+$StgUsd+'~!~'+$StgAllctd+'~!~'+"-";Write-Host $inActvSitesDD;}
        if($inActivSites -eq 0) {$inActivSites=-5;}

        $sortUsagAccDtl=@()
        $usagAccDtlArr | foreach{if($_.FileCount -ne '' -and $_.IsDeleted -eq 'FALSE'){$sortUsagAccDtl+=$_}}
        $sortUsagAccDtl|Sort-Object {$_.FileCount -as [Int]} -Descending | Select-Object -First $rptTopNDD |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};$totFilesDD='TotalFilesDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount;Write-Host $totFilesDD}
        $sortUsagAccDtl | Sort-Object {$_.ActiveFileCount -as [Int]} -Descending | Select-Object -First $rptTopNDD |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};$actFilesDD='ActivFilesDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount;Write-Host $actFilesDD}
    
        [long]$strgUsed=0
        $usagAccDtlArr | foreach{if($_."StorageUsed(Byte)" -ne '' -and $_.IsDeleted -eq 'FALSE'){$strgUsed=$strgUsed+[long]$_."StorageUsed(Byte)"}}
        $sortUsagAccDtl | Sort-Object {$_."StorageUsed(Byte)" -as [long]} -Descending | Select-Object -First $rptTopNDD |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};
        $StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5)        
        $StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)
        if([long]$_."StorageUsed(Byte)" -ge 0){$StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5) }else{$StgUsd=0}        
        if([long]$_."StorageAllocated(Byte)" -ge 0){$StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)}else{$StgAllctd=0}
        if($StgUsd -ge 0 -and $StgAllctd -gt 0){$strgUsdPcnt=[math]::Round((($StgUsd/$StgAllctd)*100),2)}else{$strgUsdPcnt=0}
        $strgUsedDD='StrgUsedDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+"-"+'~!~'+"-"+'~!~'+$StgUsd+'~!~'+$StgAllctd+'~!~'+"-"+'~!~'+$strgUsdPcnt;Write-Host $strgUsedDD}
        if([long]$strgUsed -ge 0){$strgUsedGB=[math]::Round(([long]$strgUsed/1073741824),2)}else{$strgUsedGB=0}

        [long]$strgAllocatd=0
        $usagAccDtlArr | foreach{if($_."StorageAllocated(Byte)" -ne '' -and $_.IsDeleted -eq 'FALSE'){$strgAllocatd=$strgAllocatd+[long]$_."StorageAllocated(Byte)"}}
        $sortUsagAccDtl | Sort-Object {$_."StorageAllocated(Byte)" -as [long]} -Descending | Select-Object -First $rptTopNDD |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};
        $StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5)        
        $StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)
        if([long]$_."StorageUsed(Byte)" -ge 0){$StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5) }else{$StgUsd=0}        
        if([long]$_."StorageAllocated(Byte)" -ge 0){$StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)}else{$StgAllctd=0}
        $strgUsedDD='StrgAllocatdDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+"-"+'~!~'+"-"+'~!~'+$StgUsd+'~!~'+$StgAllctd;Write-Host $strgUsedDD}
        if([long]$strgAllocatd -ge 0){$strgAllocatdGB=[math]::Round(([long]$strgAllocatd/1073741824),2)}else{$strgAllocatdGB=0}
        
        if($strgUsedGB -ge 0 -and $strgAllocatdGB -gt 0){$strgUsedPercent=[math]::Round((($strgUsedGB/$strgAllocatdGB)*100),2)}else{$strgUsedPercent=0}
        
        $maxSiteCnts=0
        $sortMaxStrgUsed=@()
        $usagAccDtlArr | foreach{
            if($_."StorageAllocated(Byte)" -ne '' -and $_.IsDeleted -eq 'FALSE'){     
                if([long]$_."StorageUsed(Byte)" -ge 0 -and $_."StorageAllocated(Byte)" -gt 0){$percent=(($_."StorageUsed(Byte)"/$_."StorageAllocated(Byte)")*100)}else{$percent=0}                        
                if($percent -ge $strgLimit){
                        $maxSiteCnts++
                        $sortMaxStrgUsed+=$_
                    }
                }
        }
        $sortMaxStrgUsed | Sort-Object {$_."StorageUsed(Byte)" -as [long]} -Descending | Select-Object -First $rptTopNDD |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};
		$StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5)        
        $StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)
        if([long]$_."StorageUsed(Byte)" -ge 0){$StgUsd=[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5) }else{$StgUsd=0}        
        if([long]$_."StorageAllocated(Byte)" -ge 0){$StgAllctd=[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)}else{$StgAllctd=0}
        if($StgUsd -ge 0 -and $StgAllctd -gt 0 ){$strgprct = ($StgUsd/$StgAllctd)*100}else{$strgprct=0}
        
        $maxStrgUsedDD='MaxStorageUsedDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+"-"+'~!~'+"-"+'~!~'+$StgUsd+'~!~'+$StgAllctd+'~!~'+'-'+'~!~'+[math]::Round($strgprct,2);Write-Host $maxStrgUsedDD}

        $usageMeasure='measures~'+$totalSites+'~'+$activSites+'~'+$activSitesPercent+'~'+$inActivSites+'~'+$strgUsedGB+'~'+$strgAllocatdGB+'~'+$strgUsedPercent+'~'+$maxSiteCnts+'~'+$orphCnt
        Write-Host $usageMeasure
    }
}Catch{
    $excepMsg=([string]$_.Exception)+($_.ScriptStackTrace)
    Write-Host 'Exception occurred -- '$excepMsg
}

if($SPOSiteDtls -and (Test-Path $SPOSiteDtls)){
    Remove-Item -Path $SPOSiteDtls
}
if($MsolUsrDtls -and (Test-Path $MsolUsrDtls)){
    Remove-Item -Path $MsolUsrDtls
}
if($ODBUsageAccDtls -and (Test-Path $ODBUsageAccDtls)){
    Remove-Item -Path $ODBUsageAccDtls
}
if($ODBUsageAccCnts -and (Test-Path $ODBUsageAccCnts)){
    Remove-Item -Path $ODBUsageAccCnts
}
[System.GC]::GetTotalMemory($true) | out-null

