##/*****************************************************************************
##Author                :               Guravareddy.T
##Purpose               :               Display The particular User Mail Box Status
##Created               :               11/1/2017
##Modified By		:
##/*****************************************************************************
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

$TestInputs=$args
$userName=$TestInputs[0]
$Password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUsr=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]

$rName=$TestInputs[4]
$RprtNameAndmbusr=$rName.split("#")
$mbuser=$RprtNameAndmbusr[0]
$reportingname=$RprtNameAndmbusr[1]
$rptPath='EXO/'+$reportingname

$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() }


$WriteLog=$true
$ManualThrottle=0
[double]$ActiveThrottle=.25
$ResetSeconds=870
$WriteLog=$true
$LogFile = "" 

# Writes output to a log file with a time date stamp
Function Write-Log {
	Param ([string]$string)

	[string]$date = Get-Date -Format G
	
    if ($WriteLog) {
    ( "[" + $date + "] - " + $string) | Out-File -FilePath $LogFile -Append } 

}

Function Start-SleepWithProgress {
	Param([int]$sleeptime)

	For ($i=0;$i -le $sleeptime;$i++){
		$timeleft = ($sleeptime - $i);
		Write-Progress -Activity "Sleeping" -CurrentOperation "$Timeleft More Seconds" -PercentComplete (($i/$sleeptime)*100);
		start-sleep 1
	}
	
	Write-Progress -Completed -Activity "Sleeping"
}

Function New-CleanO365Session {
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)
	
    $i = 0
	while (($Credential -eq $Null) -and ($i -lt 5)){
		$script:Credential = Get-Credential -Message "Please provide your Exchange Online Credentials"
		$i++
	}

	if ($Credential -eq $null){
		Write-log "[Error] - Failed to get credentials"
		Write-Error -Message "Failed to get credentials" -ErrorAction Stop
	}

	Write-Log "Removing all PS Sessions"

	Get-PSSession | Remove-PSSession -Confirm:$false
	[System.GC]::Collect()
	Write-Log ("Sleeping 15 seconds for Session Tear Down")
	Start-SleepWithProgress -SleepTime 15
	$Error.Clear()
	
	# Create the session
	Write-Log "Creating new PS Session"
	$sessionOption = New-PSSessionOption -SkipRevocationCheck
	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
	}
	$global:session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $azureEnvArr[1] -Credential $Credential -Authentication Basic -AllowRedirection -SessionOption $sessionOption -WarningAction SilentlyContinue
		
	# Check for an error while creating the session
	if ($Error.Count -gt 0 ){
	
		Write-Log "[ERROR] - Error while setting up session"
		Write-log $Error
		$ErrorCount++
		if ($ErrorCount -le 2){
		
			Write-log "[ERROR] - Failed to setup session after multiple tries"
			Start-SleepWithProgress -sleeptime 15
            New-CleanO365Session	
		}		
		
	}
	else {
		$ErrorCount = 0
	}
	
	# Import the PS session
	$null = Import-PSSession $session -AllowClobber -WarningAction SilentlyContinue -DisableNameChecking
	
	# Set the Start time for the current session
	Set-Variable -Scope script -Name SessionStartTime -Value (Get-Date)
}


$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value

$MyDir=$egInstallpath.Value+'/agent/EXO/'+$reportingname

if(!(Test-Path -Path $MyDir )){
    New-Item -ItemType directory -Path $MyDir
}

$LogFile = $MyDir+"\UserMapiCon.log"
$LogFile1 = $MyDir+"\UserMapiCon1.log"

if ($WriteLog -eq $true){ #if flag is true 
    if ([System.IO.File]::Exists($LogFile) -and (Get-Item $LogFile).length -gt 2mb) { #if the size of file is greater than 1MB 
        if([System.IO.File]::Exists($LogFile1)){ #if logfile1 already exists, delete logfile1 
            Remove-Item $LogFile1 
        } 

        Rename-Item $LogFile $LogFile1 
    }
}


$havingoutput=$false
 try{
    New-CleanO365Session    
    if($global:session.Availability -eq 'Available' -and $global:session.State -eq 'opened')
    {
        $starttime=Get-Date
        $Usermapicon = Eg-WriteFile -ComntRptPath $rptPath -FileName "usermapi" -keyFileName "Kusermapi" -EgPath $egurkhaPath
        $error.Clear()
        $output=Test-MapiConnectivity -Identity $mbuser | select * 
        if($error)
        {

            Write-log $error  # if input wrong or user doent exits in the domain
            Write-Host 'status failed'
            exit
        }
        $endtime=Get-Date
        $timediffere=NEW-TIMESPAN –Start $starttime –End $endtime | select TotalSeconds
        if($output)
        {
        [array]$newObject = [PSCustomObject][ordered]@{
            Server=$output.Server
            Database=$output.Database
            Result=$output.Result
            Latency=$output.Latency
            Error=$output.Error
            Mailbox=$output.Mailbox
            MailboxGuid=$output.MailboxGuid
            Connecttime=($timediffere.TotalSeconds).ToString().replace(',','.')
        }

        $newObject | Export-Csv  $Usermapicon[1] 
        $havingoutput=$true
    }

    }

  }Catch{
            $ErrorMessage = $_.Exception.Message
            write-Log ("ErrorMessage while running User Mapi Connectivity : "+$ErrorMessage)  
        } 
  
    if($havingoutput)
    {
        $null=Protect-File  $Usermapicon[1] -Algorithm AES -KeyAsPlainText $Usermapicon[0] -RemoveSource       
    } 
 
    try{
        $readfiles=Eg-ReadFile -ComntRptPath $rptPath -FileName "usermapi" -keyFileName "kusermapi" -EgPath $egurkhaPath
        $datafile=$readfiles[1] -replace (".csv",".dat") 
        $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
        $measure= import-csv $csvfile
        Remove-Item $csvfile
        Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'usermapi' -InputFile $readfiles[3]
        Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kusermapi' -InputFile $readfiles[4]
        Write-Host "ReadFile:"$readfiles[3]

    }catch{
        Write-Log  "File not found. The location does not contain usermapi files."
        Write-Error -Message "File not found. The $reportingname location does not contain usermapi files."
     } 
  
if($measure){

    Write-Host connectingtime $measure.Connecttime
    $usrstatus=$measure.Result
    Write-Host status $usrstatus
    $mbguid=($measure.Mailbox)+'('+$measure.MailboxGuid+')'
    Write-Host ddvalues  $measure.Server ~!~ $measure.Database ~!~ $mbguid ~!~ $measure.Result ~!~ $measure.Latency ~!~ $measure.Error

}
else
{
    Write-Host 'status failed'
}


Write-Log "Script Complete Destroying PS Sessions"
Get-PSSession | Remove-PSSession -Confirm:$false
