@Library('xmos_jenkins_shared_library@v0.35.0')

def runningOn(machine) {
    println 'Stage running on:'
    println machine
}

getApproval()
pipeline {
    agent {label 'documentation'}

    parameters {
      string(
        name: 'TOOLS_VERSION',
        defaultValue: '15.3.0',
        description: 'The XTC tools version'
      )
    } // parameters

    environment {
      REPO_NAME = "AN02014"
      XMOSDOC_VERSION = "v6.2.0"
    }

    options {
        skipDefaultCheckout()
        timestamps()
        buildDiscarder(xmosDiscardBuildSettings(onlyArtifacts = false))
    } // options

    stages {
      stage('Checkout') {
        steps{
          runningOn(env.NODE_NAME)
          dir(env.REPO_NAME){
            checkout scm
            withTools(params.TOOLS_VERSION) {
              // clone the sandbox
              sh "cmake -B app_dsp_and_usb/build"
              createVenv('requirements.txt')
              withVenv {
                sh 'pip install -r requirements.txt'
              } // venv
            } // tools
          }
        }
      } // steps
      stage("Build and Docs") {
        parallel {
          stage('Build') {
            steps{
              dir(env.REPO_NAME){
                withTools(params.TOOLS_VERSION) {
                  withVenv {
                    // check the notebook is clean
                    sh "jupyter nbconvert --clear-output app_dsp_and_usb/dsp.ipynb --output=clean && diff app_dsp_and_usb/dsp.ipynb app_dsp_and_usb/clean.ipynb"
                    // run the notebook and save the output
                    sh "jupyter nbconvert --execute --to html --output=an app_dsp_and_usb/dsp.ipynb"
                    archiveArtifacts artifacts: "app_dsp_and_usb/an.html"
                    sh 'find app_dsp_and_usb/bin -name "*.xe" | grep .'  // fails if binaries don't exist
                  } // venv
                } // tools
              }
            } // steps
          } // build

          stage('Docs') {
            steps {
              dir(env.REPO_NAME){
                withTools(params.TOOLS_VERSION) {
                  withVenv {
                    buildDocs()
                  } // venv
                } // tools
              }
            } // steps
          } // docs
        } // parallel
      } // build and docs
      stage("Archive Sandbox") {
        steps {
          sh "rm -rf .get_tools && git -C ${env.REPO_NAME} clean -xdf"
          zip zipFile: "${env.REPO_NAME}_sandbox.zip", archive: true
        }
      }
    } // stages
    post {cleanup {cleanWs()}} // post
} // pipeline
