param (
    [Parameter(Mandatory=$true)][string]$batchScript
)

<#
To set args for debugging in ISE edit then paste these into the 
PS command prompt or select then press F8.

$PSDefaultParameterValues.clear()
$PSDefaultParameterValues.add("TimeBatch.ps1:batchScript","runbatch.cmd")
$PSDefaultParameterValues
#>


function runProcess($cmdLine,$argList,$workingFolder)
{
        #write-host "runProcess: " $cmdLine $argList $workingFolder
        $pinfo = New-Object System.Diagnostics.ProcessStartInfo
        $pinfo.FileName = $cmdLine
        $pinfo.Arguments = $argList
        $pinfo.RedirectStandardError = $true
        $pinfo.RedirectStandardOutput = $true
        $pinfo.WorkingDirectory = $workingFolder
        $pinfo.UseShellExecute = $false

        $p = New-Object System.Diagnostics.Process
        $p.StartInfo = $pinfo
        $p.Start() | Out-Null
        $stdout = $p.StandardOutput.ReadToEnd()
        $stderr = $p.StandardError.ReadToEnd()
        $p.WaitForExit()
        $output = $stdout + $stderr
        #return $output
}

function getResult($report, $status)
{
   $results = ""
   foreach ($line in $report.Split([Environment]::NewLine)) 
   {        
        if ($line.Contains($status))
        { 
            $RegexOptions = [System.Text.RegularExpressions.RegexOptions]
            $csvSplit = ' = '
            $parts = [regex]::Split($line, $csvSplit, $RegexOptions::ExplicitCapture)

            $result = $parts[1]
            $result = $result -replace '\s+', ' '
            
            return $result
        }
   }
}

function run()
{   
   $TestBed = (Get-ChildItem Env:TestBed).Value
   #write-Host $TestBed
   if (-Not (Test-Path $TestBed ))
   {
      write-Host "Environment not ready."
      return
   }
   $WorkingFolder = $TestBed + "\batch"
   
   $run1Set = $WorkingFolder + "\run1set.cmd"
   
   if (-Not (Test-Path $run1Set))
   {
      write-Host "Cannot find batch script: " + $run1set
      return
   }
       
   Write-host "Processing: " $batchScript
   $Total = 0
   foreach ($line in Get-Content $batchScript) 
   {
       $RegexOptions = [System.Text.RegularExpressions.RegexOptions]
       $csvSplit = '( )(?=(?:[^"]|"[^"]*")*$)'

       $parts = [regex]::Split($line, $csvSplit, $RegexOptions::ExplicitCapture)      
       
       #write-Host $Line
       
       if ($parts[0].Equals("call") -AND $parts[2].Contains("gmproj"))
       {
           $projPath = $parts[2].Replace("%wrk%",$TestBed)
           
           $T = Measure-Command { $log = runProcess $run1set $projPath $WorkingFolder }
           $Total = $Total + $T.TotalSeconds
           
           $ReportFolder = [System.IO.Path]::GetDirectoryName($projPath.replace('"','')) + "\report"
           $MigStats = Get-ChildItem -Path $ReportFolder  -Filter "*MigStat.txt"
           $MigStat = $ReportFolder+"\"+$MigStats[0]
           if (-Not (Test-Path $MigStat ))
           {
              write-Host "MigStat not found in " $ReportFolder 
              return
           }
           
           $ReportData = Get-Content $MigStat
           
           $transStatus = getResult $ReportData "Translation Status"
           $buildStatus = getResult $ReportData ".NET Build Status"
           $r = "Trans=" + $transStatus + " Build=" + $buildStatus

           $rpt = "{0,-50} {1,20} {2,-40}" -f $r, ("TIME(sec)="+($T.TotalSeconds.ToString("#.0"))), $projPath
           
           write-Host $rpt          
           #exit
       }
       
   }
   write-Host ("TOTAL TIME(sec)="+$Total.ToString("#.0"))
}

run
