<#
    /*****************************************************************************
    Author            :       Prabaharan.T
    Purpose           :       display the sharepoint site usage details
    Created           :       28/03/2019
    Modified By       : 

#>

$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]
$consumeStrgPerc=$TestInputs[2]
$proxyUser=$TestInputs[3]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[4]
$proxyserver=$TestInputs[5]
$readDat=[datetime]$TestInputs[6]
$rptNam=$TestInputs[7]
$rptTopNDD=[int]$TestInputs[8]
$graphDetails=$TestInputs[9]
if($graphDetails -and $graphDetails -ne 'none'){
    $graphDetailsArr=($graphDetails).ToString() -Split ("~!~")
    $appId=$graphDetailsArr[0]
    $appSecret=$graphDetailsArr[1]
    $authString=$graphDetailsArr[2]
    $resource=$graphDetailsArr[3]
}
$appDetails=$TestInputs[10]
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'

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.Contains('none')){
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUser -ne 'none' -and $proxyPass -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.CredentialCache]::DefaultNetworkCredentials
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
}

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

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

    Process
    {
        $typePath=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
        Add-Type -Path $typePath
        $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
        }
        $queryRes = [System.Text.Encoding]::$encTyp.GetString((Invoke-WebRequest -Method Get -Headers $header -Uri $Url -UseBasicParsing).RawContentStream.ToArray())
        #$queryRes = Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url 
        $queryRes=$queryRes.Replace('ï»¿','')
        $queryRes=$queryRes.Replace('(Byte)','')
        $queryRes=$queryRes.Replace(' ','')
        $resultarray = ConvertFrom-Csv -InputObject $queryRes
        $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 -Encoding $encTyp -NoTypeInformation -Force
        }
    }
}

# Calculating ----- Site Usage Summary --------
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$SPUsageCnts=$rptPath+'\SiteUsageSiteCounts'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $SPUsageCnts
$SPUsageDtls=$rptPath+'\SiteUsageSiteDetail'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $SPUsageDtls

Eg-InvokeUrl -Url "https://graph.microsoft.com/v1.0/reports/getSharePointSiteUsageSiteCounts(period='D7')" -filePath $SPUsageCnts
Eg-InvokeUrl -Url "https://graph.microsoft.com/v1.0/reports/getSharePointSiteUsageDetail(period='D7')" -filePath $SPUsageDtls
[System.GC]::GetTotalMemory($true) | out-null
$siteCounts=Import-Csv $SPUsageCnts -Encoding $encTyp
$siteUsageDtls=Import-Csv $SPUsageDtls -Encoding $encTyp

$reportDate=$siteCounts | select ReportRefreshDate -First 1
$chkDat=$siteUsageDtls | select ReportRefreshDate -First 1
$reportDate=($reportDate.ReportRefreshDate)
$chkDat=($chkDat.ReportRefreshDate)
$isGetTnt=$false
if([datetime]$reportDate -eq [datetime]$chkDat){
    if([datetime]$reportDate -ge [datetime]$toReadDat){
        $isGetTnt=$true
        Write-Host 'ReadedDate for the Date#'$reportdate '!>'
        $sitCntData=$siteCounts |sort -Property ReportDate -Descending |Select-Object -First 1
        $cnt=0
        $totalFiles=0
        $totActFiles=0
        $totPageView=0
        $totVisitPage=0
        $totStoragUsed=0
        $totStrgAllot=0 

        $strgAltAcrosSit=0
        $siteUsageDtls|ForEach-Object{$cnt++;$totalFiles+=$_.FileCount;$totActFiles+=$_.ActiveFileCount;$totPageView+=$_.PageViewCount;$totVisitPage+=$_.VisitedPageCount;$totStoragUsed+=($_.StorageUsed/(1024*1024*1024));$totStrgAllot+=(($_.StorageAllocated -as [decimal])/(1024*1024*1024));if($strgAltAcrosSit -lt ($_.StorageAllocated -as [decimal])){$strgAltAcrosSit=($_.StorageAllocated -as [decimal])}}
        $strgAltAcrosSit=($strgAltAcrosSit/(1024*1024*1024))
        $totStoragUsed=[math]::Round($totStoragUsed,2)
        $totStrgAllot=[math]::Round($totStrgAllot,2)
   
        $actFilePercnt=[math]::Round((($totActFiles/$totalFiles)*100), 2)
        $strgUsedPercnt=[math]::Round((($totStoragUsed/$strgAltAcrosSit)*100), 2)

        $ldate=($siteUsageDtls |sort -Property LastActivityDate -Descending |Select-Object -First 1).LastActivityDate
        $lastActData=$siteUsageDtls|Where-Object{$_.LastActivityDate -in $ldate}
        $lastActData|Select-Object -First $rptTopNDD |ForEach-Object{$forWrit='LastActData#'+$_.ReportRefreshDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.IsDeleted+'~!~'+$_.LastActivityDate+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+$_.PageViewCount+'~!~'+$_.VisitedPageCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round((($_.StorageAllocated -as [decimal])/(1024*1024*1024)),2)+'~!~-~!~'+$_.RootWebTemplate+'!>';Write-Host $forWrit}

        $fileCntToSort=@()
        $siteUsageDtls | ForEach{$fileCntToSort+=New-Object PSObject -Property @{'FileCntObj'=$_;'FileCnt'=[int]$_.FileCount}}
        $top10FilesCnt=$fileCntToSort | Sort-Object FileCnt -Descending | Select-Object -First $rptTopNDD
        $top10FilesCnt.FileCntObj|ForEach-Object{$forWrit='FileCnt#'+$_.ReportRefreshDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.IsDeleted+'~!~'+$_.LastActivityDate+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+$_.PageViewCount+'~!~'+$_.VisitedPageCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round((($_.StorageAllocated -as [decimal])/(1024*1024*1024)),2)+'~!~-~!~'+$_.RootWebTemplate+'!>';Write-Host $forWrit}

        $actFileToSort=@()
        $siteUsageDtls | ForEach{$actFileToSort+=New-Object PSObject -Property @{'ActFileObj'=$_;'ActFile'=[int]$_.ActiveFileCount}}
        $top10ActFile=$actFileToSort | Sort-Object ActFile -Descending | Select-Object -First $rptTopNDD
        $top10ActFile.ActFileObj|ForEach-Object{$forWrit='ActFile#'+$_.ReportRefreshDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.IsDeleted+'~!~'+$_.LastActivityDate+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+$_.PageViewCount+'~!~'+$_.VisitedPageCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round((($_.StorageAllocated -as [decimal])/(1024*1024*1024)),2)+'~!~-~!~'+$_.RootWebTemplate+'!>';Write-Host $forWrit}

        $pagViewToSort=@()
        $siteUsageDtls | ForEach{$pagViewToSort+=New-Object PSObject -Property @{'PagViewObj'=$_;'PagView'=[int]$_.PageViewCount}}
        $top10PagView=$pagViewToSort | Sort-Object PagView -Descending | Select-Object -First $rptTopNDD
        $top10PagView.PagViewObj|ForEach-Object{$forWrit='PagView#'+$_.ReportRefreshDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.IsDeleted+'~!~'+$_.LastActivityDate+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+$_.PageViewCount+'~!~'+$_.VisitedPageCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round((($_.StorageAllocated -as [decimal])/(1024*1024*1024)),2)+'~!~-~!~'+$_.RootWebTemplate+'!>';Write-Host $forWrit}

        $visitPagToSort=@()
        $siteUsageDtls | ForEach{$visitPagToSort+=New-Object PSObject -Property @{'VisitPagObj'=$_;'VisitPag'=[int]$_.VisitedPageCount}}
        $top10VisitPag=$visitPagToSort | Sort-Object VisitPag -Descending | Select-Object -First $rptTopNDD
        $top10VisitPag.VisitPagObj|ForEach-Object{$forWrit='VisitPag#'+$_.ReportRefreshDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.IsDeleted+'~!~'+$_.LastActivityDate+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+$_.PageViewCount+'~!~'+$_.VisitedPageCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round((($_.StorageAllocated -as [decimal])/(1024*1024*1024)),2)+'~!~-~!~'+$_.RootWebTemplate+'!>';Write-Host $forWrit}

        $CnsumStrgCnt=0
        $CnsumStrgToSort=@()
        $siteUsageDtls | ForEach{$cst=0;if($_.StorageUsed -ne 0 -and ($_.StorageAllocated -as [decimal]) -ne 0){$cst=(($_.StorageUsed/($_.StorageAllocated -as [decimal]))*100);if($cst -gt $consumeStrgPerc){$CnsumStrgCnt++}};$CnsumStrgToSort+=New-Object PSObject -Property @{'CnsumStrgObj'=$_;'CnsumStrg'=[int]$cst}}
        $top10CnsumStrg=$CnsumStrgToSort| Sort-Object CnsumStrg -Descending | Select-Object -First $rptTopNDD
        $top10CnsumStrg.CnsumStrgObj|ForEach-Object{$cst=0;if($_.StorageUsed -ne 0 -and ($_.StorageAllocated -as [decimal]) -ne 0){$cst=(($_.StorageUsed/($_.StorageAllocated -as [decimal]))*100)};if($cst -gt $consumeStrgPerc){$forWrit='CnsumStrg#'+$_.ReportRefreshDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.IsDeleted+'~!~'+$_.LastActivityDate+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+$_.PageViewCount+'~!~'+$_.VisitedPageCount+'~!~'+[math]::Round(($_.StorageUsed/(1024*1024*1024)),2)+'~!~'+[math]::Round((($_.StorageAllocated -as [decimal])/(1024*1024*1024)),2)+'~!~'+$cst+'~!~'+$_.RootWebTemplate+'!>';Write-Host $forWrit}}

        $siteUse='SiteUse~'+$sitCntData.Total+'~'+$sitCntData.Active+'~'+$totalFiles+'~'+$totActFiles+'~'+$actFilePercnt+'~'+$totPageView+'~'+$totVisitPage+'~'+$CnsumStrgCnt+'~'+$totStoragUsed+'~'+$strgAltAcrosSit+'~'+$strgUsedPercnt+'!>' #$totStrgAllot
        write-host $siteUse
    } 
}

if([System.IO.File]::Exists($SPUsageCnts) -eq 'True'){
    Remove-Item $SPUsageCnts
}
if([System.IO.File]::Exists($SPUsageDtls) -eq 'True'){
    Remove-Item $SPUsageDtls
}
[System.GC]::GetTotalMemory($true) | out-null
#if Graph data available then fetch tenant details
if($isGetTnt){
    $domain=$authString.Replace('https://login.microsoftonline.com/','').Replace('.onmicrosoft.com','')
    $url = 'https://'+$domain+'-admin.sharepoint.com'
    if($appDetails -and $appDetails -ne 'none'){
	    Connect-PnPOnline -url $url -clientId $clientId -Tenant $tenantName -Thumbprint $thumbPrint -WarningAction SilentlyContinue
        Try{
            $strgQuota=(Get-PnPTenant |select StorageQuota).StorageQuota -as [long]
            $strgQuota=(($strgQuota/1024))
            $strgQuota=[math]::Round($strgQuota,2)
            $resStr='StorageQuotaMeasure~'+$strgQuota+'!>'
            Write-Host $resStr
        }Catch{
            $resStr='StorageQuotaMeasure~0!>'
            Write-Host $resStr
        }
    }else{
	    $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $password -asplaintext -force)    
    	Connect-SPOService -Url $url -Credential $cred
        Try{
            $strgQuota=(Get-SPOTenant |select StorageQuota).StorageQuota -as [long]
            $strgQuota=(($strgQuota/1024))
            $strgQuota=[math]::Round($strgQuota,2)
            $resStr='StorageQuotaMeasure~'+$strgQuota+'!>'
            Write-Host $resStr
        }Catch{
            $resStr='StorageQuotaMeasure~0!>'
            Write-Host $resStr
        }
    }
    [System.GC]::GetTotalMemory($true) | out-null
}