
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]
$proxyUser=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$proxyserver=$TestInputs[4]
$readDat=[DateTime]$TestInputs[5]

$ToReadDate=$readDat.tostring(“yyyy-MM-dd”)
$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
    )
    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
        return $reports.Usage
    }
}

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

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

$spoUsrurl= "https://graph.microsoft.com/v1.0/reports/getOffice365ServicesUserCounts(period='D7')"
$usrDtls=Eg-InvokeUrl -Url $spoUsrurl

$rptDat=$usrDtls.ReportRefreshDate
if([datetime]$rptDat -ge [datetime]$ToReadDate){
    $spoUsrDtls='UserDtls~'+$rptDat+'~'+$usrDtls.SharePointActive+'~'+$usrDtls.SharePointInactive
    Write-Host $spoUsrDtls
} 

