[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egurkhaPath=(Get-Item Env:EGURKHA_INSTALL_DIR).value.ToString()
$scriptPath =split-path -parent $MyInvocation.MyCommand.Definition
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egDatnKy -WarningAction SilentlyContinue


clear
#<#
$TestInputs=$args
$userName=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUsr=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$temp=$TestInputs[4]
$unReceivTims=$TestInputs[5]
$rptNam=$TestInputs[6]
$smtpPort=$TestInputs[7]
$useSSL=$TestInputs[8]
#>

$tempArr=$temp.Split('#')
[int]$measurePeriod=$tempArr[0]
[int]$rtim=$tempArr[1]
$lastSendTims=[String]$tempArr[2]
$isAllow=$true

$subjectStr='O365MailDeliverabilityTest '+$rptNam+' -'
$azureVal=Eg-GetAzureEnv -UserName $userName
$azureEnvArr=$azureVal.Split(',')

if($proxyUsr.toString().toLower().Trim() -eq 'none') { $proxyUsr=$proxyUsr.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim()}
if($proxyUsr -ne 'none' -and $proxyPass -ne 'none'){
    $proxyCred=New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
    $sessionOption=New-PSSessionOption -SkipRevocationCheck -ProxyAccessType WinHttpConfig -ProxyAuthentication basic -ProxyCredential $proxyCred
}
try{
    $credentials=New-Object System.Management.Automation.PSCredential($userName,(ConvertTo-SecureString $password -AsPlainText -Force))   
    $sessionOption=New-PSSessionOption -SkipRevocationCheck
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $azureEnvArr[1] -Credential $credentials -Authentication Basic -AllowRedirection -SessionOption $sessionOption -WarningAction SilentlyContinue
    $null=Import-PSSession $session -AllowClobber -WarningAction SilentlyContinue -DisableNameChecking
}catch{
    Write-Error 'Exception Occured' $_.Exception.Message 
    Write-Host 'PSsession Exception Occured'
    $isAllow=$false
}

$paramInMin=(($measurePeriod/60)*5)
if($isAllow){
    if($lastSendTims -ne $null -and $lastSendTims -ne '' -and $lastSendTims -ne 'nil'){
        $lstTimsArr=$lastSendTims -split ('~')
        $srchStr=@()
        $notReceiveMail=''
        for($i=0;$i -lt $lstTimsArr.Length;$i++){
            $notReceiveMail+='~'+$subjectStr+$lstTimsArr[$i]
            $srchStr+=$subjectStr+$lstTimsArr[$i]
        }
        if($unReceivTims -ne 'nil'){
            $unReceivTimsArr= $unReceivTims -split ('~')
            foreach($a in $unReceivTimsArr){
                $srchStr+=$subjectStr+$a
            }
            $unReceivTims='~'+$unReceivTims
        }

        # ****RECEIVE MESSAGES*****
        $todayDatFmt=Get-Date -Format 'dd/MM/yyyy'
        $todayDat=[datetime]::ParseExact($todayDatFmt,'dd/MM/yyyy',$null).ToUniversalTime()
 
        $msgTrace=Get-MessageTrace -RecipientAddress $userName -StartDate $todayDat.AddMinutes(-($paramInMin)) -EndDate $todayDat.AddDays(1) | select * |Where-Object {$_.Subject -in $srchStr}
        
        $totRndTim=0
        $maxRndTripTim=0
        $j=0      
        foreach($msg in $msgTrace){
            $receivTim=[Datetime]$msg.Received
            $replcSub='~'+$msg.Subject
            $notReceiveMail=$notReceiveMail.Replace($replcSub,'')
            $sub=$msg.Subject.Split('-')
            $sendTim=[DateTime][long]$sub[1]
            $duration = $receivTim-$sendTim
            $millsec=((($duration.Minutes*60)+($duration.Seconds))*1000)
            $totmilliSec=$millsec+$duration.Milliseconds
            if($unReceivTims -ne 'nil'){
                $curSub='~'+$sub[1]
               if($unReceivTims.Contains($curSub)) {
                    $unReceivTims=$unReceivTims.Replace($curSub,'')
                    $delayedMsgs="DelayedReceiveMsgs #"+$sendTim+'~!~'+$receivTim+'~!~'+([Math]::Round((($totmilliSec/60)/1000), 2))
                    Write-Host $delayedMsgs
               }
               if($unReceivTims -eq '' -and $unReceivTims -eq $null){$unReceivTims='nil'}
            }
            $roundTripTim=(($totmilliSec)/1000)
            $totRndTim+=$roundTripTim
            if($roundTripTim -gt $maxRndTripTim){
                $maxRndTripTim=$roundTripTim
            }
            $j++             
        }

        if($j -ne 0){
            $avgRndTim=[math]::Round((($totRndTim/$j)/60),2)
            $maxRndTripTim=[math]::Round(($maxRndTripTim/60),2)
            $totRTSec=[math]::Round($totRndTim,2)
            $recvMeasure='Receive Mail ~100~'+$j+'~'+$totRTSec+'~'+$avgRndTim+'~'+$maxRndTripTim
            Write-Host $recvMeasure
        }else{
            $recvMeasure='Receive Mail ~0~-5~-5~-5~-5'
            Write-Host $recvMeasure
        }

        #***FOR DELAYED RECEIVING MESSAGES ****
        $notReceiveTims=''
        if($notReceiveMail -ne $null -and $notReceiveMail -ne ''){
            $notReceiveTims=$notReceiveMail.Substring(1,$notReceiveMail.Length)
            $notReceiveTims=$notReceiveTims.Replace($subjectStr,'')
        }
        if($unReceivTims -ne 'nil' -or $notReceiveTims -ne ''){   
            if($notReceiveTims -ne ''){
                $notReceiveTims='NotReceive Timings #'+$notReceiveTims+$unReceivTims
            }
            else{
                $notReceiveTims='NotReceive Timings #'+$unReceivTims.Substring(1)
            }
            Write-Host $notReceiveTims
        }    
    }

    # ****DELETE MESSAGES*****
    Try{
	$exSub=$subjectStr+'*'
	$delSub='''Subject:'+'"'+$exSub+'"'''
	$null=Search-Mailbox -Identity $userName -SearchQuery $delSub -DeleteContent -WarningAction SilentlyContinue -Force
    }Catch{
	$emsg='Search-Mailbox Err Msg #'+$_.Exception.Message
        Write-Host $emsg
    }

    # *****SEND MESSAGES******
    $smtp =$azureEnvArr[2]
    $b4Cnt=0
    $aftrCnt=0
    $totSendTim=0
    $sendTimStr=''
    for($q=0;$q -lt $rtim;$q++){
        $body="Testing Mail Deliverability<br>"
        $body+="Please do not respond to this email"

        $datFmt1=Get-Date -Format 'dd/MM/yyyy HH:mm:ss ffff'
        $datTim1=[datetime]::ParseExact($datFmt1,'dd/MM/yyyy HH:mm:ss ffff',$null).ToUniversalTime()
        $subject=$subjectStr+$datTim1.Ticks
        try{
            $b4Cnt++
            if($useSSL -eq 'true'){
                Send-MailMessage -From $userName -To $userName -Subject $subject -Body $body -BodyAsHtml -smtpserver $smtp -Port $smtpPort -Credential $credentials -UseSsl -ErrorAction Stop
            }
            else{
                Send-MailMessage -From $userName -To $userName -Subject $subject -Body $body -BodyAsHtml -smtpserver $smtp -Port $smtpPort -Credential $credentials -ErrorAction Stop
            }
            $aftrCnt++
            if($q -eq 0){
                $sendTimStr=$subject
            }else{
                $sendTimStr=$sendTimStr+'~'+$subject
            }  
        }catch{
            $emsg='Sending Failed Msg #'+$_.Exception.Message
            Write-Host $emsg
	    if($emsg.Contains('The SMTP server requires a secure connection or the client was not authenticated')){break;}
            continue
        } 
        $datFmt2=Get-Date -Format 'dd/MM/yyyy HH:mm:ss ffff'
        $datTim2=[datetime]::ParseExact($datFmt2,'dd/MM/yyyy HH:mm:ss ffff',$null).ToUniversalTime()

        $sendTimDur=$datTim2-$datTim1
        $sendMillsec=((($sendTimDur.Minutes*60)+($sendTimDur.Seconds))*1000)
        $stotmilliSec=$sendMillsec+$sendTimDur.Milliseconds
        $sendTim=($stotmilliSec)/1000
        $totSendTim+=$sendTim
    }
    if($b4Cnt -eq $aftrCnt){
        $msg='Send Mail ~'+'100~'+$aftrCnt+'~'+$totSendTim
        Write-Host $msg
    }elseif($aftrCnt -ne 0){
        $msg='Send Mail ~0'+'~'+$aftrCnt+'~'+$totSendTim
        Write-Host $msg
    }
    else{
        $msg='Send Mail ~0~-5~-5'
        Write-Host $msg
    }
    $sendTimStr=$sendTimStr.Replace($subjectStr,'')
    if($sendTimStr -eq $null -or $sendTimStr -eq ''){$sendTimStr='nil'}
    $sendTimStr='SendTimeStr#'+$sendTimStr
    Write-Host $sendTimStr
}

Get-PSSession | Remove-PSSession


