@Library('xmos_jenkins_shared_library@v0.38.0')

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

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

    parameters {
      string(
        name: 'TOOLS_VERSION',
        defaultValue: '15.3.1',
        description: 'The XTC tools version'
      )
      string(
        name: 'XMOSDOC_VERSION',
        defaultValue: 'v6.3.1',
        description: 'xmosdoc version'
      )
    } // parameters

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

    stages {
      stage('Checkout') {
        steps{
          runningOn(env.NODE_NAME)
          script {
            def (server, user, repo) = extractFromScmUrl()
            env.REPO_NAME = repo
          }
          dir(env.REPO_NAME){
              checkoutScmShallow()
              withTools(params.TOOLS_VERSION) {
              // clone the sandbox
              sh "cmake -B app_an02015/build -D DEPS_CLONE_SHALLOW=TRUE"
              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_an02015/dsp.ipynb --output=clean && diff app_an02015/dsp.ipynb app_an02015/clean.ipynb"
                    // run the notebook and save the output
                    sh "jupyter nbconvert --execute --to html --output=an app_an02015/dsp.ipynb"
                    archiveArtifacts artifacts: "app_an02015/an.html"
                    sh 'find app_an02015/bin -name "*.xe" | grep .'  // fails if binaries don't exist
                    // notebook builds somewhere different to where archiveSandbox expects
                    sh 'cp -r app_an02015/build build'
                  } // 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
          {
            archiveSandbox(REPO_NAME)
          }
      }
    } // stages
    post
    {
        cleanup
        {
             xcoreCleanSandbox()
        }
    }
} // pipeline