$ErrorActionPreference = "Stop"

$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
Write-Host $env:PATH

# Windows-specific binary list. bio (biome) is Linux-only and is intentionally excluded.
# chef*/inspec* wrappers are also excluded as they are not shipped on Windows.
# If you update the binaries list in omnibus/package-scripts/cinc-workstation/postinst,
# also update this list accordingly.
$binaries = @(
  "berks",
  "cinc",
  "cinc-cli",
  "cinc-analyze",
  "cinc-apply",
  "cinc-shell",
  "cinc-solo",
  "cookstyle",
  "cinc-auditor",
  "kitchen",
  "knife",
  "ohai",
  "cinc-client",
  "cinc-zero",
  "mixlib-install",
  "fauxhai",
  "taste-tester"
)

function Get-PreferredVersionLine {
  param(
    [string[]]$Lines
  )

  foreach ($line in $Lines) {
    $trimmed = $line.Trim()
    if (-not $trimmed) { continue }
    if ($trimmed -match '^\[[^\]]+\] WARN:' -or
        $trimmed -match '^WARN:' -or
        $trimmed -match '^ERROR:' -or
        $trimmed -match '^Invalid mode:' -or
        $trimmed -match '^Usage:' -or
        $trimmed -match '^Docs:' -or
        $trimmed -match '^Website:' -or
        $trimmed -match '^Welcome to ' -or
        $trimmed -match '^The Cinc command line tool') {
      continue
    }

    if ($trimmed -match '[Vv]ersion' -or $trimmed -match '[0-9]+\.[0-9]+') {
      return $trimmed
    }
  }

  return $null
}

function Get-FirstNonEmptyLine {
  param(
    [string[]]$Lines
  )

  foreach ($line in $Lines) {
    $trimmed = $line.Trim()
    if ($trimmed) {
      return $trimmed
    }
  }

  return $null
}

function Show-VersionOutput {
  param(
    [string]$Binary
  )

  $args = @("--version", "version", "-v", "-V")
  if ($Binary -eq "mixlib-install") {
    $args = @("version", "--version", "-v", "-V")
  }

  foreach ($arg in $args) {
    $outputLines = @()
    $success = $true

    try {
      $outputLines = & $Binary $arg 2>&1 | ForEach-Object { $_.ToString() }
    }
    catch {
      $success = $false
    }

    if (-not $success) {
      continue
    }

    if ($LASTEXITCODE -ne 0) {
      continue
    }

    $line = Get-PreferredVersionLine -Lines $outputLines
    if (-not $line) {
      $line = Get-FirstNonEmptyLine -Lines $outputLines
    }

    if ($line -and ($line -match '[Vv]ersion' -or $line -match '[0-9]+\.[0-9]+')) {
      Write-Host ("{0}: {1}" -f $Binary, $line)
      return
    }
  }

  Write-Host ("{0}: no supported version flag found (skipped)" -f $Binary)
}

foreach ($binary in $binaries) {
  if (-not (Get-Command $binary -ErrorAction SilentlyContinue)) {
    throw "${binary}: command not found"
  }

  Show-VersionOutput -Binary $binary
}

cinc-auditor detect
cinc-auditor.bat exec test\integration\cinc-tests --no-distinct-exit --input=skip_known_failures=${env:SKIP_KNOWN_FAILURES} --reporter cli junit:junit.xml
