pipeline {
  agent any
  options {
    // keep build logs for troubleshooting; set as you need
    timestamps()
    skipDefaultCheckout()
  }
  parameters{
    string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).')
    string(name: 'NAME', description: 'Name of the entity in the Datadog Software catalog.')
    string(name: 'REPOSITORY_URL', description: 'URL of the entity\'s GitHub repository.')
    string(name: 'PIPELINE_URL', description: 'URL of the entity\'s Jenkins pipeline')
    string(name: 'REVISION', description: 'Hash of the commit to check out.')
    string(name: 'SERVICE_PATH', defaultValue: '', description: 'Path to the service code within the repository.')
    string(name: 'SERVICE_DEFINITION_FILE_PATH', defaultValue: '', description: 'Path to a service definition file.')
    booleanParam(name: 'FETCH_ADDITIONAL_METADATA', defaultValue: true, description: 'Whether or not to fetch metadata from external services, e.g. Sonar, Sentry, Swagger.')
  }
  stages{
    stage('Load Shared Libraries') {
      steps {
          library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
      }
    }
    stage('Checkout repo') {
      steps {
        checkout([
          $class: 'GitSCM',
          branches: [[name: params.REVISION]],
          doGenerateSubmoduleConfigurations: false,
          extensions: [[$class: 'RelativeTargetDirectory', relativeTargetDir: "./${params.NAME}"]],
          submoduleCfg: [],
          userRemoteConfigs: [[credentialsId: 'pipeline-jenkins-github-app', url: params.REPOSITORY_URL]]
        ])
        script {
          currentBuild.description = "${params.NAME}:${params.REVISION}."
        }
      }
    }
    stage('Validate Software Catalog Definition') {
      steps {
        dir("./${params.NAME}") {
          datadogSoftwareCatalogValidate(
            servicePath: params.SERVICE_PATH,
            serviceDefinitionFilePath: params.SERVICE_DEFINITION_FILE_PATH
          )
        }
      }
    }
    stage('Publish Software Catalog Definition') {
      steps {
        dir("./${params.NAME}") {
          datadogSoftwareCatalogPublish(
            repositoryUrl: params.REPOSITORY_URL,
            pipelineUrl: params.PIPELINE_URL,
            servicePath: params.SERVICE_PATH,
            fetchAdditionalMetadata: params.FETCH_ADDITIONAL_METADATA,
            serviceDefinitionFilePath: params.SERVICE_DEFINITION_FILE_PATH
          )
        }
      }
    }
  }
}
