/**
 * (c) Copyright IBM Corporation 2015.
 * (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
 * This is licensed under the following license.
 * The Eclipse Public 1.0 License (http://www.eclipse.org/legal/epl-v10.html)
 * U.S. Government Users Restricted Rights:  Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */

import com.urbancode.air.plugin.AppScanSaaS.NewAirPluginTool
import com.urbancode.air.plugin.AppScanSaaS.SCXRestClient
import com.urbancode.air.plugin.AppScanSaaS.SastScanHelper
import com.urbancode.air.plugin.AppScanSaaS.ScanType

import java.io.*
import groovy.json.JsonSlurper
import groovy.json.JsonOutput

final def airHelper = new NewAirPluginTool(args[0], args[1])
final Properties props = airHelper.getStepProperties()

String appId = props["applicationId"]
String scaFileLocation = props['scaFileLocation']
String issueCountString = props['reportIssueCountValidation']
long scanTimeout = props["scanTimeout"] ? Long.parseLong(props["scanTimeout"]) : -1
boolean mailNotification = props['mailNotification']
boolean failOnPause = Boolean.parseBoolean(props['failOnPause'])
boolean validateReport = !issueCountString.isEmpty()
int exitCode = 0

SCXRestClient restClient = new SCXRestClient(props)
SastScanHelper scanHelper = new SastScanHelper()

if (!scaFileLocation) {
    println "[Error] IRX file/Scan directory has not been specified."
    System.exit 1
}

File scaFile = new File(scaFileLocation)
if (!scaFile.exists()) {
    println "[Error] SCA file $scaFile doesn't exist."
    System.exit 1
}

boolean isGenerateARSA = !(scaFile.name.endsWith('.irx') || scaFile.name.endsWith('.arsa'))

if (isGenerateARSA) {
    String arsaToolDir = props['arsaToolDir']

    if (!arsaToolDir) {
        println "[Error] Static Analyzer Client Tool location has not been specified."
        System.exit 1
    }

    String encryptArsa = props['encryptArsa']
    boolean encrypt = true

    if (encryptArsa) {
        encrypt = Boolean.parseBoolean(encryptArsa)
    }

    scaFile = scanHelper.generateARSA(arsaToolDir, scaFile, props["scaConfigFile"], encrypt)

    if (!scaFile.exists()) {
        println("[Error] IRX file generation failed.")
        System.exit(1)
    }
}

String scanId = restClient.startScaScan(scaFile, appId, mailNotification)

if (isGenerateARSA) {
    scaFile.delete()
}

airHelper.setOutputProperty("ScanId", scanId)
airHelper.storeOutputProperties()

if (validateReport) {
    long startTime = System.currentTimeMillis()
    def scan = restClient.waitForScan(scanId, ScanType.SCA, startTime, scanTimeout, failOnPause)
    def issuesJson = scan.LatestExecution
    def issuesJson1 = JsonOutput.toJson(issuesJson)
    def slurper = new JsonSlurper()
    def issuesJson2 = slurper.parseText(issuesJson1)

    exitCode = restClient.validateScanIssues(issuesJson2, scan.Name, scanId, issueCountString)
}

if (exitCode) {
    println("[Error] Scan has failed validation.")
}
else {
    println("[OK] Scan has completed successfully.")
}

System.exit(exitCode)