$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]
$graphDetails=$TestInputs[7]
if($graphDetails -and $graphDetails -ne 'none'){
    $graphDetailsArr=($graphDetails).ToString() -Split ("~!~")
    $appId=$graphDetailsArr[0]
    $appSecret=$graphDetailsArr[1]
    $authString=$graphDetailsArr[2]
    $resource=$graphDetailsArr[3]
}
#>

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

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

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

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$SPOUsrActvtyDtlCSV=$rptPath+'\SPOUsrActvtyDtl'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $SPOUsrActvtyDtlCSV
$url = "https://graph.microsoft.com/v1.0/reports/getSharePointActivityUserDetail(period='D7')"
while($true){
    Eg-InvokeGraphUrl -Url $url -filePath $SPOUsrActvtyDtlCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource
    $SPOUsrActvtytotal=Import-Csv $SPOUsrActvtyDtlCSV -Encoding $encTyp
    $url=$SPOUsrActvtytotal.'@odata.nextLink'
    if($url -eq $null -or $url -eq ''){
        break
    }
}
$diffence=(NEW-TIMESPAN –Start $readingdate –End (Get-Date) | Select-Object Days).Days
[System.GC]::GetTotalMemory($true) | out-null
$notFirsttime = $false
while($diffence -ge 1)
{
    if($notFirsttime){ $readingdate=$readingdate.AddDays(1) }
    $actualdate=$readingdate
    $notFirsttime = $true
    $SPOUsrActivity =$SPOUsrActvtytotal | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
    if($SPOUsrActivity)
    {
        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
}
[System.GC]::GetTotalMemory($true) | out-null
$SPOUsrActivity = $SPOUsrActivity | Where-Object { $_.UserPrincipalName -ne '(Unknown)' } 
Write-Host '#MeasuresStart#'
foreach($usr in $SPOUsrActivity) {
    $hasLicenses=0
    $assignedProducts=$usr.AssignedProducts
    if($assignedProducts -and $assignedProducts.Trim().Length -gt 0){
        $hasLicenses=1
    }
    Write-Host $usr.UserPrincipalName'#' $usr.ViewedOrEditedFileCount '#' $usr.SyncedFileCount '#' $usr.SharedInternallyFileCount '#' $usr.SharedExternallyFileCount '#' $usr.VisitedPageCount '#' $hasLicenses
}
Write-Host '#MeasuresEnd#'
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($SPOUsrActvtyDtlCSV) -eq 'True'){
    Remove-Item $SPOUsrActvtyDtlCSV
}