#!groovy

pipeline {

  // agent defines where the pipeline will run.
  agent {  
    label {
      label "sl7cloud"
    }
  }
  
  triggers {
    pollSCM('H/2 * * * *')
  }

  // The options directive is for configuration that applies to the whole job.
  options {
    buildDiscarder(logRotator(numToKeepStr:'5', daysToKeepStr: '7'))
    timeout(time: 60, unit: 'MINUTES')
    disableConcurrentBuilds()
    timestamps()
    office365ConnectorWebhooks([[
                    name: "Office 365",
                    notifyBackToNormal: true,
                    startNotification: false,
                    notifyFailure: true,
                    notifySuccess: false,
                    notifyNotBuilt: false,
                    notifyAborted: false,
                    notifyRepeatedFailure: true,
                    notifyUnstable: true,
                    url: "${env.MSTEAMS_URL}"
            ]]
    )
  }

  stages {  
    stage("Checkout") {
      steps {
        echo "Branch: ${env.BRANCH_NAME}"
        checkout scm
      }
    }
    
    stage("Build for Python 3") {
      steps {
        echo "Build Number: ${env.BUILD_NUMBER}"
        script {
            env.GIT_COMMIT = sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
            env.GIT_BRANCH = sh(returnStdout: true, script: 'git rev-parse --abbrev-ref HEAD').trim()
            echo "git commit: ${env.GIT_COMMIT}"
            echo "git branch: ${env.BRANCH_NAME} ${env.GIT_BRANCH}"
            // env.BRANCH_NAME is only supplied to multi-branch pipeline jobs
            if (env.BRANCH_NAME == null) {
                env.BRANCH_NAME = "master"
            }

            if (env.BRANCH_NAME != null && env.BRANCH_NAME.startsWith("Release")) {
                env.IS_RELEASE = "YES"
                env.RELEASE_VERSION = "${env.BRANCH_NAME}".replace('Release_', '')
                echo "release version: ${env.RELEASE_VERSION}"
            }
            else {
                env.IS_RELEASE = "NO"
                env.RELEASE_VERSION = ""
            }
        }
        
        sh """
            git clean -fqdx
            export BUILD_NUMBER=${env.BUILD_NUMBER}
            export BRANCH_NAME=${env.BRANCH_NAME}
            export GIT_COMMIT=${env.GIT_COMMIT}
            export RELEASE_BRANCH=${env.RELEASE_VERSION}
            export RELEASE=${env.IS_RELEASE}
            cd package_builder
            sh jenkins_build_python.sh
            """
      }
    }
    stage("Report Unit Tests python 3") {
      steps {
        junit '**/test-reports/TEST-*.xml'
      }
   }
    stage("Trigger Downstream") {
      steps {
        build job: 'ibex_gui_linux_pipeline', wait: false
      }
    }
  }
  post {
    always {
       archiveArtifacts artifacts: 'docs/_build/html/**/*', caseSensitive: false
    }
  }
}
