node {
    def app
    def full_image_name = 'deepfenceio/jenkins-example:latest'
    def deepfence_mgmt_console_ip = '111.111.111.111' // IP address of Deepfence management console
    def fail_cve_count = 100 // Fail jenkins build if number of vulnerabilities found is >= this number. Set -1 to pass regardless of vulnerabilities.
    def fail_cve_score = 8 // Fail jenkins build if cumulative CVE score is >= this value. Set -1 to pass regardless of cve score.

    stage('Clone repository') {
        checkout scm
    }

    stage('Build image') {
        app = docker.build("${full_image_name}", "-f ci-cd-integrations/jenkins/Dockerfile .")
    }

    stage('Run Deepfence Vulnerability Mapper'){
        DeepfenceAgent = docker.image("deepfenceio/deepfence_vulnerability_mapper_ce:latest")
        try {
            c = DeepfenceAgent.run("-it --net=host -v /var/run/docker.sock:/var/run/docker.sock", "-mgmt-console-ip=${deepfence_mgmt_console_ip} -image-name=${full_image_name} -fail-cve-count=${fail_cve_count} -fail-cve-score=${fail_cve_score}")
            sh "docker logs -f ${c.id}"
            def out = sh script: "docker inspect ${c.id} --format='{{.State.ExitCode}}'", returnStdout: true
            sh "exit ${out}"
        } finally {
            c.stop()
        }
    }

    stage('Remove unused docker image') {
        sh "docker rmi ${full_image_name}"
    }
}
