<#
    /*****************************************************************************
    Author            :       Logesh
    Purpose           :       Display's One Drive device usage by user
    Created           :       21/07/2020
    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]
$proxyUser=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$readingdate=[datetime]$TestInputs[4]
$proxyserver=$TestInputs[5]
$rptNam=$TestInputs[6]
#>

$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')){
    $proxyserverip='http://'+$proxyserver
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserverip)
    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=$readingdate.tostring(“yyyy-MM-dd”)
$rptPath=$egurkhaPath+'\agent\ODB\'+$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 -Encoding $encTyp -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))
$DeviceUsgByUsrCSV=$rptPath+'\DeviceUsgByUsr'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $DeviceUsgByUsrCSV

Eg-InvokeUrl -Url "https://graph.microsoft.com/v1.0/reports/getOneDriveUsageAccountDetail(period='D7')" -filePath $DeviceUsgByUsrCSV


$TotalDeviceUsgByUsr=Import-Csv $DeviceUsgByUsrCSV -Encoding $encTyp

$enddate=Get-date
$diffence=(NEW-TIMESPAN –Start $readingdate –End (Get-Date) | Select-Object Days).Days

$notFirsttime = $false
while($diffence -ge 1)
{
    if($notFirsttime){ $readingdate=$readingdate.AddDays(1) }
    $actualdate=$readingdate
    $notFirsttime = $true
    $TotalDeviceUsg =$TotalDeviceUsgByUsr | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
    if($TotalDeviceUsg)
    {
        Write-Host 'ReadDate for the Date#'$actualdate.tostring(“yyyy-MM-dd”)
        break
    }
    else
    {
        Write-Host 'thereIs No Data on#'$actualdate.tostring(“yyyy-MM-dd”)
    }
    $diffence=$diffence-1
}

Write-Host '#MeasuresStart#'
foreach($dev in $TotalDeviceUsg) {
    Write-Host $dev.OwnerPrincipalName'#' $dev.FileCount '#' $dev.ActiveFileCount '#' $dev.'StorageUsed' '#' $dev.'StorageAllocated'
}
Write-Host '#MeasuresEnd#'
if([System.IO.File]::Exists($DeviceUsgByUsrCSV) -eq 'True'){
    Remove-Item $DeviceUsgByUsrCSV
}
