pipeline {
  agent any

  options {
    ansiColor('xterm')
    disableConcurrentBuilds()
    timestamps()
  }

  parameters {
    string(name: 'CHECKOV_IMAGE_TAG', defaultValue: 'latest', description: 'The tag of the terraform-static-code-analysis image to use to scan the Terraform code.')
    string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag or Git revision.')
  }

  triggers {
    issueCommentTrigger('.*retest this please.*')
  }

  stages {
    stage('Load Shared Libraries') {
      steps {
        library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
      }
    }

    stage('Validate Software Catalog Definitions') {
      steps {
        script {
          def files = []
          if (fileExists('software-catalog.yaml')) {
            files = [[name: 'software-catalog.yaml', path: 'software-catalog.yaml']]
          } else {
            files = findFiles(glob: 'software-catalog/*.yaml').collect { [name: it.name, path: it.path] }
          }

          if (!files || files.size() == 0) {
            error "No Datadog catalog files found. Provide software-catalog.yaml or software-catalog/*.yaml"
          }

          currentBuild.description = files.collect { it.name }.join('<br>')

          parallel(files.collectEntries { f ->
            [(f.name): {
              datadogSoftwareCatalogValidate(serviceDefinitionFilePath: f.path)
            }]
          })
        }
      }
    }

    stage('Terraform Scan') {
      when {
        not { branch 'master' }
      }
      steps {
        terraformScan(checkovImageTag: params.CHECKOV_IMAGE_TAG)
      }
    }

    stage('Publish Software Catalog Definitions') {
      when {
        branch 'master'
      }
      steps {
        script {
          def files = []
          if (fileExists('software-catalog.yaml')) {
            files = [[name: 'software-catalog.yaml', path: 'software-catalog.yaml']]
          } else {
            files = findFiles(glob: 'software-catalog/*.yaml').collect { [name: it.name, path: it.path] }
          }

          parallel(files.collectEntries { f ->
            [(f.name): {
              datadogSoftwareCatalogPublish(serviceDefinitionFilePath: f.path)
            }]
          })
        }
      }
    }
  }
}
