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

$numOfIteratn=''
$perfRes=''
$outFile=''

$tstPath=$egurkhaPath+'\agent\SBO'
$numOfIteratn='3'
$perfRes=$tstPath+'\performance_results.tsv'
$outFile=$tstPath+'\connectivity_results.txt'


if(!(Test-Path -Path $tstPath )){
   $null= New-Item -ItemType directory -Path $tstPath
}

$nwrkAssessDir=''
$drives =gdr -PSProvider 'FileSystem' | select name
foreach($drv in $drives){
    $path=$drv.Name+':\*\Microsoft Skype for Business Network Assessment Tool'
    Try{
        $nwAsses=Get-Childitem $path -Recurse
        $nwrkAssessDir=$nwAsses.Directory[0].ToString()
        if($nwrkAssessDir -ne '' -and $nwrkAssessDir -ne $null){
            break
        }
    }Catch{}
}

if($nwrkAssessDir -ne '' -and $nwrkAssessDir -ne $null){

    $filePath=$nwrkAssessDir+'\NetworkAssessmentTool.exe.config'
    $writPath=$nwrkAssessDir+'\NetworkAssessmentTool.exe.config1'
    $userNam=$env:UserDomain+'\'+$env:UserName
    [System.GC]::GetTotalMemory($true) | out-null

    #FOLDER PERMISSION
    $acl = Get-Acl $nwrkAssessDir
    $acl.setOwner([System.Security.Principal.NTAccount]$userNam)
    $permission = $userNam,"FullControl","Allow"
    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.SetAccessRule($accessRule)
    $acl | Set-Acl $nwrkAssessDir
    #Set-ItemProperty $nwrkAssessDir -name IsReadOnly -value $false

    #FILE PERMISSION
    $acl = Get-Acl $filePath
    $acl.setOwner([System.Security.Principal.NTAccount]$userNam)
    $permission = $userNam,"FullControl","Allow"
    $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
    $acl.SetAccessRule($accessRule)
    $acl | Set-Acl $filePath
    Set-ItemProperty $filePath -name IsReadOnly -value $false

    get-content $filePath|ForEach-Object{$val='';if($_.Contains('value')){$val=$_.Substring($_.IndexOf('value="')+7);$val=$val.Substring(0,$val.IndexOf('"/>'));$val=$val.ToString()}if($_.Contains('NumIterations') -and $numOfIteratn -ne '' -and $val -ne ''){$_ -replace $val,$numOfIteratn}elseif($_.Contains('ResultsFilePath') -and $perfRes -ne '' -and $val -ne ''){$_.Replace($val,$perfRes)}elseif($_.Contains('OutputFilePath') -and $outFile -ne '' -and $val -ne ''){$_.Replace($val,$outFile)}else{$_}}|set-content $writPath -Force
    Remove-Item $filePath
    Rename-Item $writPath $filePath
    write-host '***Permissions provided successfully ********'
}else{
    write-host '***Operation failed ********'
}
[System.GC]::GetTotalMemory($true) | out-null