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

#>

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 -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]
#>

$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
}
$o365Domain=Eg-GetDomain -userName $username -Password $password -proxyUsr $proxyUser -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver

Function Eg-InvokeUrl(){
	[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=1)]
        [String]$Url,
        [Parameter(Mandatory=$true, Position=2)]
        [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
        }
        $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 -NoTypeInformation -Force
        }
    }
}

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

#------Get App Reg Details ------------
$GraphDir=$egurkhaPath+'\agent\O365\MsGraph'
$unProtPath=$GraphDir+'\GraphDetails.dat'
$keyFileNam='\GraphDetailsKey.dat'
$kvalue=Get-Content -Path $GraphDir$keyFileNam
$null=Unprotect-File $unProtPath -Algorithm AES -KeyAsPlainText $kvalue -DstSuffix '.ini'
$spoGraphDtls=$GraphDir+"\GraphDetails.ini"
$getInputs=Get-Content -Path $spoGraphDtls
Remove-Item $spoGraphDtls
$flag=$false
foreach($input in $getInputs){
    if($input.StartsWith('[') -and $input.ToLower().Contains($o365Domain.ToLower())){
        $flag=$true
    }
    if($flag){
        if($input.Contains("client_id")){
            $appId=$input.ToString().Substring($input.IndexOf('~')+1)
        }
        if($input.Contains("client_secret")){
            $appSecret=$input.ToString().Substring($input.IndexOf('~')+1)
        }
        if($input.Contains("TenantName")){
            $tenantID=$input.ToString().Substring($input.IndexOf('~')+1)
        }
        if($input.Contains("Authority")){
            $authString=$input.ToString().Substring($input.IndexOf('~')+1)
            $authString=$authString+$o365Domain
        }
        if($input.Contains("Resource")){
            $resource=$input.ToString().Substring($input.IndexOf('~')+1)
            $flag=$false
        }
    }         
}
# Calculating ----- Site Usage Summary --------
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$SPUsageCnts=$rptPath+'\SiteUsageSiteCounts'+$timenow+'.csv'
$SPUsageDtls=$rptPath+'\SiteUsageSiteDetail'+$timenow+'.csv'

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

$siteCounts=Import-Csv $SPUsageCnts
$siteUsageDtls=Import-Csv $SPUsageDtls

$reportDate=$siteCounts | select ReportRefreshDate -First 1
$chkDat=$siteUsageDtls | select ReportRefreshDate -First 1
$reportDate=($reportDate.ReportRefreshDate)
$chkDat=($chkDat.ReportRefreshDate)
if([datetime]$reportDate -eq [datetime]$chkDat){
    if([datetime]$reportDate -ge [datetime]$toReadDat){
        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 

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

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

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

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

Remove-Item $SPUsageCnts
Remove-Item $SPUsageDtls
