<#
    /*****************************************************************************
    Author            :       Mounika Kuna
    Purpose           :       Provides Users Mails and Mailboxes Details
    Created           :       15/09/2020    
    /*****************************************************************************
#>
$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]
$proxyserver=$TestInputs[4]
$strgLimit=$TestInputs[5]
$toreadDate_UsrsMailbx=[datetime]$TestInputs[6]
$toreadDate_UsrsMailactvty=[datetime]$TestInputs[7]
$toreadDate_UsrsMailAppUsg=[datetime]$TestInputs[8]
$rptNam=$TestInputs[9]
$rchRecvrQuotaLmt=$TestInputs[10]
$graphDetails=$TestInputs[11]
$appDetails=$TestInputs[12]
$debug=$false
try{
    $debug=$TestInputs[13]
}catch{
$debug=$false
}


if($graphDetails -and $graphDetails -ne 'none'){
    $graphDetailsArr=($graphDetails).ToString() -Split ("~!~")
    $appId=$graphDetailsArr[0]
    $appSecret=$graphDetailsArr[1]
    $authString=$graphDetailsArr[2]
    $resource=$graphDetailsArr[3]
}
if($appDetails -and $appDetails -ne 'none'){
    $appDetailsArr=($appDetails).ToString() -Split ("~!~")
    $clientId=$appDetailsArr[0]
    $tenantName=$appDetailsArr[1]
    $thumbPrint=$appDetailsArr[2]
}
#>

$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')){
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    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
    }
}

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

$allDomains=''
if($rptNam -match '_exd'){
    $dhash=@{}
    $dmnshash=Eg-O635Domains -username $username -password $password -rptNam $rptNam -proxyserverip $proxyserver -proxyUsr $proxyUser -proxyPass $proxyPass -appDetails $appDetails
    $hashVal=[String]$dmnshash[$rptNam]
    $allDomns=$hashVal.Split('~')
    if($allDomns.Count -gt 0){
        $allDomains=$allDomns[0]
    }
}

$rptPath=$egurkhaPath+'\agent\EXO\'+$rptNam+'\usermailsnmailbox'
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

Function DeleteDatFiles(){
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, Position=1)]
        [String]$FilePath, 
        [Parameter(Mandatory=$true, Position=2)]
        [String]$Pattern
    )
    Process
    {
        $FilePath=$FilePath+'\'
        $count=1
        $fileRead=Get-ChildItem -Path $FilePath |Where-Object {$_.Name -like $Pattern+'*.dat' }| Sort-Object LastWriteTime -Descending | Select Name 
        foreach($file in $fileRead){
            if($count -gt 2){
                $fileNameTemp=([String]$file.Name).Trim()
                $keyFileName=$FilePath+'k'+$fileNameTemp
                $fileName=$FilePath+$fileNameTemp
                if([System.IO.File]::Exists($keyFileName) -eq 'True'){
                    Remove-Item $keyFileName -Force
                }
                if([System.IO.File]::Exists($fileName) -eq 'True'){
                    Remove-Item $fileName -Force
                }
            }
            $count++ 
        }
    }
}

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
if($debug -and $debug -ne 'false'){
    $keyName='\kMailboxUsageDetail'+ $timenow + ".dat"
    $key=Get-CryptoKey -FileDir $rptPath -FileName $keyName
}
$MailboxUsageDetailCSV=$rptPath+'\MailboxUsageDetail'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $MailboxUsageDetailCSV

$url1 = "https://graph.microsoft.com/v1.0/reports/getMailboxUsageDetail(period='D7')"
$TotalMailboxUsageDetail=@()
while($true){
    Eg-InvokeGraphUrl -Url $url1 -filePath $MailboxUsageDetailCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource
    if($rptNam -match '_exd'){
        $csvOut=Import-Csv $MailboxUsageDetailCSV -Encoding $encTyp
        foreach($res in $csvOut){
            $domainUsr=$res.UserPrincipalName
            if($domainUsr -ne $null -and $domainUsr -ne ''){
                $usrDmn=$domainUsr.Split('@')[1]
                if($allDomains -match $usrDmn){
                    $TotalMailboxUsageDetail+=$res
                }
            }
        }   
    }else{
        $TotalMailboxUsageDetail=Import-Csv $MailboxUsageDetailCSV -Encoding $encTyp
    }
    $url1=$TotalMailboxUsageDetail.'@odata.nextLink'
    if($url1 -eq $null -or $url1 -eq ''){
        break
    }
}
$firstRecord1=$TotalMailboxUsageDetail | select ReportRefreshDate -First 1
$ReportRefreshDate1=($firstRecord1.ReportRefreshDate)
$diffence1=(NEW-TIMESPAN –Start $toreadDate_UsrsMailbx –End $ReportRefreshDate1 | Select-Object Days).Days
if($diffence1 -ge 1){$reportRefreshed1=$true}
if($debug -and $debug -ne 'false'){
    $null=Protect-File  $MailboxUsageDetailCSV -Algorithm AES -KeyAsPlainText $key -RemoveSource
}

[System.GC]::GetTotalMemory($true) | out-null
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
if($debug -and $debug -ne 'false'){
    $keyName2='\kUserEmailActivities'+ $timenow + ".dat"
    $key2=Get-CryptoKey -FileDir $rptPath -FileName $keyName2
}
$UserEmailActivitiesCSV=$rptPath+'\UserEmailActivities'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $UserEmailActivitiesCSV

$url2 = "https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail(period='D7')"
$UserEmailActivities=@()
while($true){
    Eg-InvokeGraphUrl -Url $url2 -filePath $UserEmailActivitiesCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource
    if($rptNam -match '_exd'){
        $csvOut=Import-Csv $UserEmailActivitiesCSV -Encoding $encTyp
        foreach($res in $csvOut){
            $domainUsr=$res.UserPrincipalName
            if($domainUsr -ne $null -and $domainUsr -ne ''){
                $usrDmn=$domainUsr.Split('@')[1]
                if($allDomains -match $usrDmn){
                    $UserEmailActivities+=$res
                }
            }
        }   
    }else{
        $UserEmailActivities=Import-Csv $UserEmailActivitiesCSV -Encoding $encTyp
    }
    $url2=$UserEmailActivities.'@odata.nextLink'
    if($url2 -eq $null -or $url2 -eq ''){
        break
    }
}
$firstRecord2=$UserEmailActivities | select ReportRefreshDate -First 1
$ReportRefreshDate2=($firstRecord2.ReportRefreshDate)
$diffence2=(NEW-TIMESPAN –Start $toreadDate_UsrsMailactvty –End $ReportRefreshDate2 | Select-Object Days).Days
if($diffence2 -ge 1){$reportRefreshed2=$true}
if($debug -and $debug -ne 'false'){
    $null=Protect-File  $UserEmailActivitiesCSV -Algorithm AES -KeyAsPlainText $key2 -RemoveSource
}
[System.GC]::GetTotalMemory($true) | out-null
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
if($debug -and $debug -ne 'false'){
    $keyName3='\kMailAppUsage'+ $timenow + ".dat"
    $key3=Get-CryptoKey -FileDir $rptPath -FileName $keyName3
}
$MailAppUsageCSV=$rptPath+'\MailAppUsage'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $MailAppUsageCSV

$url3 = "https://graph.microsoft.com/v1.0/reports/getEmailAppUsageUserDetail(period='D7')"
$TotalMailAppUsage=@()
while($true){
    Eg-InvokeGraphUrl -Url $url3 -filePath $MailAppUsageCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource 
    if($rptNam -match '_exd'){
        $csvOut=Import-Csv $MailAppUsageCSV -Encoding $encTyp
        foreach($res in $csvOut){
            $domainUsr=$res.UserPrincipalName
            if($domainUsr -ne $null -and $domainUsr -ne ''){
                $usrDmn=$domainUsr.Split('@')[1]
                if($allDomains -match $usrDmn){
                    $TotalMailAppUsage+=$res
                }
            }
        }   
    }else{
        $TotalMailAppUsage=Import-Csv $MailAppUsageCSV -Encoding $encTyp
    }
    $url3=$TotalMailAppUsage.'@odata.nextLink'
    if($url3 -eq $null -or $url3 -eq ''){
        break
    }
}
$firstRecord3=$TotalMailAppUsage | select ReportRefreshDate -First 1
$ReportRefreshDate3=($firstRecord3.ReportRefreshDate)
$diffence3=(NEW-TIMESPAN –Start $toreadDate_UsrsMailAppUsg –End $ReportRefreshDate3 | Select-Object Days).Days
if($diffence3 -ge 1){$reportRefreshed3=$true}
if($debug -and $debug -ne 'false'){
    $null=Protect-File  $MailAppUsageCSV -Algorithm AES -KeyAsPlainText $key3 -RemoveSource
}
[System.GC]::GetTotalMemory($true) | out-null
if($reportRefreshed1 -and $reportRefreshed2 -and $reportRefreshed3){
    $diffence=(NEW-TIMESPAN –Start $toreadDate_UsrsMailbx –End (Get-Date) | Select-Object Days).Days
    $notFirsttime = $false
    while($diffence -ge 1)
    {
        if($notFirsttime){ $toreadDate_UsrsMailbx=$toreadDate_UsrsMailbx.AddDays(1) }
        $actualdate=$toreadDate_UsrsMailbx
        $notFirsttime = $true
        $TotalMailboxUsage =$TotalMailboxUsageDetail | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
        if($TotalMailboxUsage)
        {
            Write-Host 'ReadDate of UsersMailbox Data on#'$actualdate.tostring(“yyyy-MM-dd”)
            break
        }
        else
        {
            Write-Host 'thereIs No UsersMailbox Data on#'$actualdate.tostring(“yyyy-MM-dd”)
        }
        $diffence=$diffence-1
    }
	[System.GC]::GetTotalMemory($true) | out-null
    $diffence=(NEW-TIMESPAN –Start $toreadDate_UsrsMailactvty –End (Get-Date) | Select-Object Days).Days
    $notFirsttime = $false
    while($diffence -ge 1)
    {
        if($notFirsttime){ $toreadDate_UsrsMailactvty=$toreadDate_UsrsMailactvty.AddDays(1) }
        $actualdate=$toreadDate_UsrsMailactvty
        $notFirsttime = $true
        $UserEmailAct =$UserEmailActivities | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
        if($UserEmailAct)
        {
            Write-Host 'ReadDate of UsersMailActivity Data on#'$actualdate.tostring(“yyyy-MM-dd”)
            break
        }
        else
        {
            Write-Host 'thereIs No UsersMailActivity Data on#'$actualdate.tostring(“yyyy-MM-dd”)
        }
        $diffence=$diffence-1
    }
	[System.GC]::GetTotalMemory($true) | out-null
    $diffence=(NEW-TIMESPAN –Start $toreadDate_UsrsMailAppUsg –End (Get-Date) | Select-Object Days).Days
    $notFirsttime = $false
    while($diffence -ge 1)
    {
        if($notFirsttime){ $toreadDate_UsrsMailAppUsg=$toreadDate_UsrsMailAppUsg.AddDays(1) }
        $actualdate=$toreadDate_UsrsMailAppUsg
        $notFirsttime = $true
        $TotalMailAppUsg =$TotalMailAppUsage | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
        if($TotalMailAppUsg)
        {
            Write-Host 'ReadDate of UsersMailAppUsage Data on#'$actualdate.tostring(“yyyy-MM-dd”)
            break
        }
        else
        {
            Write-Host 'thereIs No UsersMailAppUsage Data on#'$actualdate.tostring(“yyyy-MM-dd”)
        }
        $diffence=$diffence-1
    }
	[System.GC]::GetTotalMemory($true) | out-null
}
$TotalMailboxUsage = $TotalMailboxUsage | Where-Object { $_.UserPrincipalName -ne '(Unknown)' -and $_.IsDeleted -ne 'True'} 
foreach($User in $TotalMailboxUsage){
    $ItemCount=$User.ItemCount

    if([long]$User.StorageUsed -ge 0){$StorageUsd=[math]::Round(([long]$User.StorageUsed/1073741824),2)}else{$StorageUsd=0}          
    if($User.DeletedItemSize -ge 0){ $DeletedItemSize=[math]::Round(($User.DeletedItemSize/1073741824),2) }else{ $DeletedItemSize=0 }
    if([long]$User.IssueWarningQuota -ge 0){$IssueWarningQuotaD=[math]::Round(([long]$User.IssueWarningQuota/1073741824),2)}else{ $IssueWarningQuotaD=0 }        
    if([long]$User.ProhibitSendQuota -ge 0){$ProhibitSendQuotaD=[math]::Round(([long]$User.ProhibitSendQuota/1073741824),2)}else{$ProhibitSendQuotaD=0}        
    if([long]$User.'ProhibitSend/ReceiveQuota' -ge 0){$ProhibitSendReceiveQuotaD=[math]::Round(([long]$User.'ProhibitSend/ReceiveQuota'/1073741824),2)}else{$ProhibitSendReceiveQuotaD=0}    

    if($StorageUsd -ge 0 -and $IssueWarningQuotaD -gt 0){ $IssueWarningQuotaLimit =($StorageUsd/$IssueWarningQuotaD)*100 }else{$IssueWarningQuotaLimit=0}                                
    if($IssueWarningQuotaLimit -ge $strgLimit){ 
        $ReachingIssueWarningQuotaLimit=1 
    }else{ 
        if($DeletedItemSize -ge 0 -and $IssueWarningQuotaD -gt 0){ $IssueWarningQuotaLimit =($DeletedItemSize/$IssueWarningQuotaD)*100 }else{$IssueWarningQuotaLimit=0}
        
        if($IssueWarningQuotaLimit -ge $strgLimit){ 
            $ReachingIssueWarningQuotaLimit=1 
        }else{
            $ReachingIssueWarningQuotaLimit=0 
        }
    } 
    
    if($StorageUsd -ge 0 -and $ProhibitSendQuotaD -gt 0){ $ProhibitSendQuotaLimit =($StorageUsd/$ProhibitSendQuotaD)*100 }else{$ProhibitSendQuotaLimit=0}  
    if($ProhibitSendQuotaLimit -ge $strgLimit){ 
        $ReachingProhibitSendQuotaLimit=1 
    }else{
        if($DeletedItemSize -ge 0 -and $ProhibitSendQuotaD -gt 0){ $ProhibitSendQuotaLimit =($DeletedItemSize/$ProhibitSendQuotaD)*100 }else{$ProhibitSendQuotaLimit=0}  
        
        if($ProhibitSendQuotaLimit -ge $strgLimit){ 
            $ReachingProhibitSendQuotaLimit=1 
        }else{ 
            $ReachingProhibitSendQuotaLimit=0 
        }
    }   
    
    if($StorageUsd -ge 0 -and $ProhibitSendReceiveQuotaD -gt 0){ $ProhibitSendRecvQuotaLimit =($StorageUsd/$ProhibitSendReceiveQuotaD)*100 }else{$ProhibitSendRecvQuotaLimit=0}
    if($ProhibitSendRecvQuotaLimit -ge $strgLimit){ 
        $ReachingProhibitSendRecvQuotaLimit=1 
    }else{ 
        if($DeletedItemSize -ge 0 -and $ProhibitSendReceiveQuotaD -gt 0){ $ProhibitSendRecvQuotaLimit =($DeletedItemSize/$ProhibitSendReceiveQuotaD)*100 }else{$ProhibitSendRecvQuotaLimit=0}

        if($ProhibitSendRecvQuotaLimit -ge $strgLimit){ 
            $ReachingProhibitSendRecvQuotaLimit=1 
        }else{
            $ReachingProhibitSendRecvQuotaLimit=0 
        }
    }
        
    
    $DeletedItemCount=$User.DeletedItemCount    
    
    $UserID=$User.UserPrincipalName

    $rchedRecvrQuota=''
    $rcvQuotaPercent=[math]::Round((($User.DeletedItemSize/$User.DeletedItemQuota)*100),2)
    if($rcvQuotaPercent -gt $rchRecvrQuotaLmt){
        $rchedRecvrQuota='1'
    }else{
        $rchedRecvrQuota='0'
    }
    
    $Output='MailboxUsage~'+$UserID+'~'+$ItemCount+'~'+$StorageUsd+'~'+$IssueWarningQuotaD+'~'+$ProhibitSendQuotaD+'~'+$ProhibitSendReceiveQuotaD+'~'+$ReachingIssueWarningQuotaLimit+'~'+$ReachingProhibitSendQuotaLimit+'~'+$ReachingProhibitSendRecvQuotaLimit+'~'+$DeletedItemCount+'~'+$DeletedItemSize+'~'+$rchedRecvrQuota
    Write-Host $Output 
}
[System.GC]::GetTotalMemory($true) | out-null
if($debug -and $debug -ne 'false'){
    DeleteDatFiles -FilePath $rptPath -Pattern 'MailboxUsageDetail'
}else{
    if([System.IO.File]::Exists($MailboxUsageDetailCSV) -eq 'True'){
        Remove-Item $MailboxUsageDetailCSV
    }
}

$UserEmailAct = $UserEmailAct | Where-Object { $_.UserPrincipalName -ne '(Unknown)' -and $_.IsDeleted -ne 'True'} 
foreach($User in $UserEmailAct){
        $hasLicenses=0
        $assignedProducts=$User.AssignedProducts
        if($assignedProducts -and $assignedProducts.Trim().Length -gt 0){
            $hasLicenses=1
        }
        $UserPrincipalName=$User.UserPrincipalName
        $SendCount=$User.SendCount
        $ReceiveCount=$User.ReceiveCount
        $ReadCount=$User.ReadCount        
        $Output = 'EmailActivity~'+$UserPrincipalName+'~'+$SendCount+'~'+$ReceiveCount+'~'+$ReadCount+'~'+$hasLicenses
        Write-Host $Output        
}
[System.GC]::GetTotalMemory($true) | out-null
if($debug -and $debug -ne 'false'){
    DeleteDatFiles -FilePath $rptPath -Pattern 'UserEmailActivities'
}else{
    if([System.IO.File]::Exists($UserEmailActivitiesCSV) -eq 'True'){
        Remove-Item $UserEmailActivitiesCSV
    }
}

$TotalMailAppUsg = $TotalMailAppUsg | Where-Object { $_.UserPrincipalName -ne '(Unknown)' -and $_.IsDeleted -ne 'True'} 
foreach($Apps in $TotalMailAppUsg){
    #----------------MailForMac ---------------------
    if($Apps.MailForMac -eq ""){$MailForMac = "0"}elseif($Apps.MailForMac -eq "Undetermined"){$MailForMac = "1"}else{$MailForMac="2"}
    #---------------OutlookForMac---------------------
    if($Apps.OutlookForMac -eq ""){$OutlookForMac = "0"}elseif($Apps.OutlookForMac -eq "Undetermined"){$OutlookForMac = "1"}else{$OutlookForMac="2"}             
    #---------------OutlookForWindows---------------------
    if($Apps.OutlookForWindows -eq ""){$OutlookForWindows = "0"}elseif($Apps.OutlookForWindows -eq "Undetermined"){$OutlookForWindows = "1"}else{$OutlookForWindows="2"}        
    #---------------OutlookForMobile---------------------
    if($Apps.OutlookForMobile -eq ""){$OutlookForMobile = "0"}elseif($Apps.OutlookForMobile -eq "Undetermined"){$OutlookForMobile = "1"}else{$OutlookForMobile="2"}
    #---------------OtherForMobile---------------------
    if($Apps.OtherForMobile -eq ""){$OtherForMobile = "0"}elseif($Apps.OtherForMobile -eq "Undetermined"){$OtherForMobile = "1"}else{$OtherForMobile="2"}        
    #---------------OutlookForWeb---------------------
    if($Apps.OutlookForWeb -eq ""){$OutlookForWeb = "0"}elseif($Apps.OutlookForWeb -eq "Undetermined"){$OutlookForWeb = "1"}else{$OutlookForWeb="2"}
    #---------------POP3App---------------------
    if($Apps.POP3App -eq ""){$POP3App = "0"}elseif($Apps.POP3App -eq "Undetermined"){$POP3App = "1"}else{$POP3App="2"}
    #---------------IMAP4App---------------------
    if($Apps.IMAP4App -eq ""){$IMAP4App = "0"}elseif($Apps.IMAP4App -eq "Undetermined"){$IMAP4App = "1"}else{$IMAP4App="2"}
    #---------------SMTPApp---------------------
    if($Apps.SMTPApp -eq ""){$SMTPApp = "0"}elseif($Apps.SMTPApp -eq "Undetermined"){$SMTPApp = "1"}else{$SMTPApp="2"}

$MailAppUsage='AppUsage~'+$Apps.UserPrincipalName+'~'+$MailForMac+'~'+$OutlookForMac+'~'+$OutlookForWindows+'~'+$OutlookForMobile+'~'+$OtherForMobile+'~'+$OutlookForWeb+'~'+$POP3App+'~'+$IMAP4App+'~'+$SMTPApp
Write-Host $MailAppUsage
}
[System.GC]::GetTotalMemory($true) | out-null
if($debug -and $debug -ne 'false'){
    DeleteDatFiles -FilePath $rptPath -Pattern 'MailAppUsage'
}else{
    if([System.IO.File]::Exists($MailAppUsageCSV) -eq 'True'){
        Remove-Item $MailAppUsageCSV
    }
}