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
Import-Module MsOnline -ea 0 -WarningAction SilentlyContinue
Import-Module Microsoft.Online.SharePoint.PowerShell -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]
#>

$domain=Eg-GetDomain -userName $username -Password $password -proxyUsr $proxyUser -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver
$o365_domain=$domain.Substring(0,$domain.IndexOf('.onmicrosoft.com'))
$url = 'https://'+$o365_domain+'-admin.sharepoint.com'
if(!$proxyserver.ToString().ToLower().Contains('none')){
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUsr.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
}

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

$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $password -asplaintext -force)    
Connect-MsolService -Credential $cred
Connect-SPOService -Url $url -Credential $cred

$rptPath=$egurkhaPath+'\agent\ODB\'+$rptNam
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$SPOSiteDtls=$rptPath+'\ODBSPOSiteDtls'+$timenow+'.csv'
$MsolUsrDtls=$rptPath+'\ODBMsolUsrDtls'+$timenow+'.csv'

Get-SPOSite -IncludePersonalSite $true -Limit all -Filter "Url -like '-my.sharepoint.com/personal/'"|select url,Owner | Export-Csv $SPOSiteDtls -Append -NoTypeInformation -Force
Get-MsolUser |Export-Csv $MsolUsrDtls -Append -NoTypeInformation -Force

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

$orphCnt=0
foreach($sitDtl in $SPOSiteDtlArr){
    if($MsolUsrDtlArr.SignInName -notcontains $sitDtl.Owner){
        $orphanDD='OrphanedSites~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+"-"+'~!~'+$sitDtl.Url
        Write-Host $orphanDD
        $orphCnt++
    }
}
if($orphCnt -eq 0){
    $orphCnt=-5
}


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

$toReadDat=$readDat.tostring(“yyyy-MM-dd”)
$azureVal=Eg-GetAzureEnv -UserName $username -subject 'O365_Graph'
$azureEnvArr=$azureVal.Split(',')
$clientArr=Get-GraphClientSecret -InitialDomain $domain
if($clientArr -ne $null){
    $clientId=$clientArr[0].ToString().Trim()
    $clientSecret=$clientArr[1].ToString().Trim()
}
$authStr=$azureEnvArr[0].ToString().Trim()+$domain
$resourceStr=$azureEnvArr[1].ToString().Trim()

$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 $clientId, $clientSecret
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authStr
        $context = $authContext.AcquireTokenAsync($resourceStr, $creds).Result
        $authCode=$context.CreateAuthorizationHeader()
        $header = @{
            'Authorization'=$authCode
        }

        $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 -Append -NoTypeInformation -Force
        }
    }
}

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

$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
    $usagAccCntsArr=Import-Csv $ODBUsageAccCnts

    $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
        
        $totalSites=0
        $activSites=0
        $usagAccCntsArr|foreach{if($_.ReportDate -eq $ldate){$totalSites=[int]$_.Total;$activSites=[int]$_.Active}}
        $activSitesPercent=[math]::Round((($activSites/$totalSites)*100),2)

        $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 25 |foreach{$inActvSitesDD='InactiveSitesDD~'+$_.LastActivityDate+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+$_.FileCount+'~!~'+$_.ActiveFileCount+'~!~'+[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5)+'~!~'+[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2)+'~!~'+"-";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 20 |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 20 |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 20 |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};$strgUsedDD='StrgUsedDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+"-"+'~!~'+"-"+'~!~'+[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5)+'~!~'+[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2);Write-Host $strgUsedDD}
        $strgUsedGB=[math]::Round(([long]$strgUsed/1073741824),2)

        [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 20 |foreach{$lstActDat='-';if($_.LastActivityDate -ne $null -and $_.LastActivityDate -ne ''){$lstActDat=$_.LastActivityDate};$strgUsedDD='StrgAllocatdDD~'+$lstActDat+'~!~'+$_.SiteURL+'~!~'+$_.OwnerDisplayName+'~!~'+"-"+'~!~'+"-"+'~!~'+[math]::Round(([long]$_."StorageUsed(Byte)"/1073741824),5)+'~!~'+[math]::Round(([long]$_."StorageAllocated(Byte)"/1073741824),2);Write-Host $strgUsedDD}
        $strgAllocatdGB=[math]::Round(([long]$strgAllocatd/1073741824),2)

        $strgUsedPercent=[math]::Round((($strgUsedGB/$strgAllocatdGB)*100),2)

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

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

Remove-Item -Path $SPOSiteDtls
Remove-Item -Path $MsolUsrDtls

Remove-Item -Path $ODBUsageAccDtls
Remove-Item -Path $ODBUsageAccCnts


