/*
    Copyright (C) 2022 Tenable, Inc.

	Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

		http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package vulnerability

import (
	"io"
	"time"

	"github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"
	"github.com/tenable/terrascan/test/helper"
)

const (
	// ScanCommand is terrascan's scan command
	ScanCommand string = "scan"

	// FindVulnerabilityFlag is terrascan's flag used with scan command
	FindVulnerabilityFlag string = "--find-vuln"

	// VulnerabilityScanTimeout is default Vulnerability Scan timeout
	VulnerabilityScanTimeout time.Duration = 2 * time.Minute
)

// RunScanAndVerifyVulnerabilityCount runs the scan command with supplied parameters and checks scan summary output
func RunScanAndVerifyVulnerabilityCount(terrascanBinaryPath string, exitCode, expectedCount int, outWriter, errWriter io.Writer, args ...string) {
	session := RunScanCommandWithFindVulnerability(terrascanBinaryPath, exitCode, outWriter, errWriter, args...)
	helper.CheckSummaryForVulnerabilities(session, expectedCount)
}

// RunScanCommandWithFindVulnerability with --find-vuln flag executes the scan command, validates exit code
func RunScanCommandWithFindVulnerability(terrascanBinaryPath string, exitCode int, outWriter, errWriter io.Writer, args ...string) *gexec.Session {
	argList := []string{ScanCommand, FindVulnerabilityFlag}
	argList = append(argList, args...)
	session := helper.RunCommand(terrascanBinaryPath, outWriter, errWriter, argList...)
	gomega.Eventually(session, VulnerabilityScanTimeout).Should(gexec.Exit(exitCode))
	return session
}
