$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()
$sboDir=$egurkhaPath+'\agent\SBO'
if(!(Test-Path -Path $sboDir )){
    $null=New-Item -ItemType directory -Path $sboDir
}

$WriteLog=$true
$isFrstTimLog=$true
$LogFile = $sboDir+"\SBOCallConnectivity.log"
$LogFile1 = $sboDir+"\SBOCallConnectivity.log"
Function Write-Log {
	Param ([string]$string)
	[string]$date = Get-Date -Format G
    if ($WriteLog) {
       ( "[" + $date + "] - "+ $string ) | Out-File -FilePath $LogFile -Append } 
    if($isFrstTimLog){     
        if ($WriteLog -eq $true){ #if flag is true 
            if ([System.IO.File]::Exists($LogFile) -and (Get-Item $LogFile).length -gt 1mb) {  #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 
            }
        }
        $isFrstTimLog=$false
    }
}
Write-Log("[INFO] ------------------------- SBOCALL CONNECTIVITY - START --------------------------------- ")
$metriInput=''
$nwAsses=Get-Childitem "C:\*\Microsoft Skype for Business Network Assessment Tool" -Recurse
$nwrkAssessDir=$nwAsses.Directory[0].ToString()
Write-Log("[INFO] - Network Assesment Directory path is -->> "+$nwrkAssessDir)
$stdOutCallDtls=$sboDir+'\SBOCallsDtlsStdOut.txt'
$stdOut90metric=$sboDir+'\SBO90MetricStdOut.txt'
$stdOutConnChk=$sboDir+'\SBOConnChkStdOut.txt'
[System.GC]::GetTotalMemory($true) | out-null
#----------Call Details-------------
push-location $nwrkAssessDir
$exe=$nwrkAssessDir+'\NetworkAssessmentTool.exe'
Write-Log("[INFO] -  NetworkAssessmentTool path is -->> "+$exe)
Start-Process -FilePath $exe -Wait -WindowStyle Hidden -RedirectStandardOutput $stdOutCallDtls

$callInitiate=0
$callComplted=0
$callFailed=0
$flag=$false
$cntnt=Get-Content -Path $stdOutCallDtls
for($j=0;$j -lt $cntnt.Length;$j++){
    Write-Log("[NetworkAssessmentTool] - content -->> "+$cntnt[$j])
    if($cntnt[$j].Contains('Starting new call')){
        $callInitiate++
        $flag=$true    
    }
    if($cntnt[$j].Contains('Call completed')){
        $callComplted++
    }
    if($cntnt[$j].ToLower().Contains('error')){
        if($flag){
            $callFailed++
            $flag=$false
        }
        $errorDD='CallErrorDD#-~!~-~!~-~!~-~!~-~!~-~!~-~!~Call '+$callInitiate+': '+$cntnt[$j]+'~!~-'
        Write-Host $errorDD
    }
    if($cntnt[$j].StartsWith('Result has been written to:')){
        $cutStr='Result has been written to: '
        $metriInput=$cntnt[$j].Substring($cutStr.Length).Trim().ToString()
    }
}
$meaOutPut=$callInitiate.ToString()+'~'+$callComplted.ToString()+'~'+$callFailed.ToString()
Write-Log("[NetworkAssessmentTool] - meaOutPut -->> "+$meaOutPut)


if($metriInput -ne $null -and $metriInput -ne ''){
    #----90th percentile-------
    $exe = $nwrkAssessDir+'\ResultsAnalyzer.exe'
    Write-Log("[ResultsAnalyzer] - exe -->> "+$exe)
    Start-Process -FilePath $exe -ArgumentList $metriInput -Wait -WindowStyle Hidden -RedirectStandardOutput $stdOut90metric
    $metricCntnt=Get-Content -Path $stdOut90metric
    $packetLoss=''
    $rttLatency=''
    $jittr=''
    $packtReOrder=''
    for($i=0;$i -lt $metricCntnt.Length;$i++){
        if(($metricCntnt[$i] -match '90th percentile values per') -or ($metricCntnt[$i] -contains '90th percentile values per')){
            $i++
            $packetLoss=$metricCntnt[$i].Substring(22)
            $packetLoss=$packetLoss.Substring(0,$packetLoss.Length-1)
            Write-Log("[ResultsAnalyzer] - packetLoss -->> "+$packetLoss)
            $i++
            $rttLatency=$metricCntnt[$i].Substring(22)
            Write-Log("[ResultsAnalyzer] - rttLatency -->> "+$rttLatency)
            $i++
            $jittr=$metricCntnt[$i].Substring(22)
            Write-Log("[ResultsAnalyzer] - jittr -->> "+$jittr)
            $i++
            $packtReOrder=$metricCntnt[$i].Substring(22)
            $packtReOrder=$packtReOrder.Substring(0,$packtReOrder.Length-1)
            Write-Log("[ResultsAnalyzer] - packtReOrder -->> "+$packtReOrder)
        }
    }
    $packetLoss=[math]::Round($packetLoss,2)
    $rttLatency=[math]::Round($rttLatency,2)
    $jittr=[math]::Round($jittr,2)
    $packtReOrder=[math]::Round($packtReOrder,2)
    Write-Log("[ResultsAnalyzer] - packetLoss&rttLatency&jittr&packtReOrder -->> "+$packetLoss+" -- "+$rttLatency+" -- "+$jittr+" -- "+$packtReOrder)

    if(($packetLoss -eq $null -or $packetLoss -eq 0) -and ($rttLatency -eq $null -or $rttLatency -eq 0) -and ($jittr -eq $null -or $jittr -eq 0) -and ($packtReOrder -eq $null -or $packtReOrder -eq 0)){
        Write-Log("[ResultsAnalyzer] - Reading from SBO90MetricStdOut.txt failed.... so read from performance_results.tsv  ")
        $packetLoss=0
        $rttLatency=0
        $jittr=0
        $packtReOrder=0
        $itraMetric=Get-Content -Path $metriInput
        $Tab = [char]9
        for($k=0;$k -lt $itraMetric.Length;$k++){
            if($k -gt 0){
                $ilineArr=$itraMetric[$k].Split($Tab)
                if($packetLoss -lt [Double]($ilineArr[1].Trim())){
                    $packetLoss=[Double]$ilineArr[1]
                }
                if($rttLatency -lt [Double]($ilineArr[2].Trim())){
                    $rttLatency=[Double]$ilineArr[2]
                }
                if($jittr -lt [Double]($ilineArr[5].Trim())){
                    $jittr=[Double]$ilineArr[5]
                }
                if($packtReOrder -lt [Double]($ilineArr[6].Trim())){
                    $packtReOrder=[Double]$ilineArr[6]
                }
            }
        }
        $packetLoss=($packetLoss*100)
        
        $packetLoss=$packetLoss.ToString().Replace(',','.')
        $rttLatency=$rttLatency.ToString().Replace(',','.')
        $jittr=$jittr.ToString().Replace(',','.')
        $packtReOrder=$packtReOrder.ToString().Replace(',','.')

        $rsltAnalzer=([math]::Round($packetLoss,2)).ToString()+'~'+([math]::Round($rttLatency,2)).ToString()+'~'+([math]::Round($jittr,2)).ToString()+'~'+([math]::Round($packtReOrder,2)).ToString()
    }else{
        $rsltAnalzer=$packetLoss.ToString()+'~'+$rttLatency.ToString()+'~'+$jittr.ToString()+'~'+$packtReOrder.ToString()
    }
    Write-Log("[ResultsAnalyzer] - rsltAnalzerOutput -->> "+$rsltAnalzer)

    $itraMetric=Get-Content -Path $metriInput
    $Tab = [char]9
    for($k=0;$k -lt $itraMetric.Length;$k++){
        if($k -gt 0){
            $iline=$itraMetric[$k].Replace($Tab,'~')
            $iline=$iline.Replace('~','~!~')
            $iline=$iline.Replace(',','.')
            $ntItrea='NetworkItreationsDD#'+$iline+'~!~-~!~-'
            Write-Log("[NetworkItreationsDD] - ntItrea -->> "+$ntItrea)
            Write-Host $ntItrea
        }
    }

    # ---------Connection Check--------------
    $exe=$nwrkAssessDir+'\NetworkAssessmentTool.exe'
    $connchkStatus='Success'
    $arg='/connectivitycheck /verbose'
    Write-Log("[connectivitycheck] - exe -->> "+$exe+$arg)
    Start-Process -FilePath $exe -ArgumentList $arg -Wait -WindowStyle Hidden -RedirectStandardOutput $stdOutConnChk
    $isFailed=$false
    $connChkCnt=Get-Content -Path $stdOutConnChk
     foreach ($connOut in $connChkCnt){
        if($connOut.ToLower().contains('not reachable')){
            $outc='ConnchkDD#'+'-~!~-~!~-~!~-~!~-~!~-~!~-~!~-~!~'+$connOut
            Write-Host $outc
            Write-Log("[connectivitycheck] - out -->> "+$outc)
            $connchkStatus='Failure'
        }
     }

    $measr='SBOCallConnMeas#'+$meaOutPut+'~'+$connchkStatus+'~'+$rsltAnalzer
    write-host $measr
    Write-Log("[Measures] - Output -->> "+$measr)

    $outputFile= Split-Path $metriInput -leaf
    $dirPth=$metriInput.Substring(0,$metriInput.IndexOf($outputFile)).Trim()
    $connChk=$dirPth+'connectivity_results.txt'

    if([System.IO.File]::Exists($metriInput) -eq 'True'){
        Remove-Item $metriInput
    }
    if([System.IO.File]::Exists($connChk) -eq 'True'){
        Remove-Item $connChk -Force
    }
    if([System.IO.File]::Exists($stdOutCallDtls) -eq 'True'){
        Remove-Item $stdOutCallDtls
    }
    if([System.IO.File]::Exists($stdOut90metric) -eq 'True'){
        Remove-Item $stdOut90metric
    }
    if([System.IO.File]::Exists($stdOutConnChk) -eq 'True'){
        Remove-Item $stdOutConnChk
    }
    [System.GC]::GetTotalMemory($true) | out-null
}else{
    Write-Error "File path not found or not accessible to execute NetworkAssessmentTool.exe!"
}

Write-Log("[INFO] --------------------------------- END ------------------------------------- ")



