pipeline {
    agent { node { label 'linux'; } }

    options { buildDiscarder(logRotator(numToKeepStr: '5')) }

    environment {
       DOC_DEPLOYER = credentials('Doc deployment')
    }

    stages {
        stage('Preparation') {
            steps {
                script {
                    branchName = 'release/2.1'
                    cred = '0c503fb7-7bad-459f-81f1-71467b382d39'

                    env.PYTHON_VENV = """${sh(
                       returnStdout:true,
                       script: 'echo "${WORKSPACE}/${BUILD_TAG}"'
                     )}"""
                }
            }
        }
        stage('Source') { // for display purposes
            steps {
                git branch: branchName, credentialsId: cred, url: 'https://git.aquila-consortium.org/Aquila-Consortium/borg_public.git'

                sh 'python3 -m venv ${PYTHON_VENV}'
                sh 'ls && echo ${PYTHON_VENV} && ls ${PYTHON_VENV}'
                sh 'test -e ${PYTHON_VENV}'

                sh 'git submodule init'
                sh 'git submodule update --recursive'
            }
        }
        stage('Download deps') {
            steps {
                ansiColor('xterm') {
                    sh '''
                      bash build.sh --download-deps
                    '''
                }
            }
        }
        stage('Configure') {
            steps {
                ansiColor('xterm') {
                    sh '''
                      . ${WORKSPACE}/${BUILD_TAG}/bin/activate
                      CMAKE_PREFIX_PATH=${VIRTUAL_ENV}:/opt/boost
                      export CMAKE_PREFIX_PATH
                      bash build.sh --python --use-system-boost=/opt/boost --use-system-fftw --use-system-hdf5 --native --purge --extra-flags -DINSTALL_PYTHON_LOCAL=OFF
                    '''
                }
            }
        }
        stage('Build') {
            steps {
                ansiColor('xterm') {
                    dir('build') {
                        sh 'make -j6'
                    }
                }
            }
        }
        stage('Tests') {
            steps {
                dir('build') {
                    sh 'make test'
                }
            }
        }
        stage('Install') {
            steps {
                dir('build') {
                    sh 'make install'
                }
            }
        }
        stage("Doc") {
            steps {
                dir('docs') {
                    sh """
                      . ${WORKSPACE}/${BUILD_TAG}/bin/activate
                      pip3 install wheel
                      pip3 install -r requirements.txt
                      rm -fr source/_generate
                      rm -fr _build
                      make SHELL=/bin/bash html
                      tar -C _build/html -zcvf doc.tgz .
                      curl -v -F filename=doc -F file=@doc.tgz http://athos.iap.fr:9595/deploy-doc2/$DOC_DEPLOYER/v2.1-public
                    """
                }
            }
        }
    }
    post {
        failure {
            notifyBuild("FAIL")
        }
        success {
            notifyBuild("SUCCESS")
        }
        cleanup {

            /* clean up our workspace */
            //deleteDir()
            /* clean up tmp directory */

            //dir("${WORKSPACE}/${BUILD_TAG}") {
            //    deleteDir()
            //}
            dir("${workspace}@tmp") {
                deleteDir()
            }
            dir("extra/hades@tmp") {
                deleteDir()
            }
            dir("extra/borg@tmp") {
                deleteDir()
            }
            dir("extra/ares_fg@tmp") {
                deleteDir()
            }
            dir("extra/python@tmp") {
                deleteDir()
            }
        }
    }
}

def notifyBuild(String buildStatus = 'STARTED') {
  // build status of null means successful
  buildStatus = buildStatus ?: 'SUCCESS'

  // Default values
  def colorName = 'RED'
  def colorCode = '#FF0000'
  def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
  def summary = "${subject} (${env.BUILD_URL})"

  // Override default values based on build status
  if (buildStatus == 'STARTED') {
    color = 'YELLOW'
    colorCode = '#0000FF'
  } else if (buildStatus == 'SUCCESS') {
    color = 'GREEN'
    colorCode = '#00FF00'
  } else {
    color = 'RED'
    colorCode = '#FF0000'
  }

  def details = """<p>STARTED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
    <p>Check console output at &QUOT;<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>&QUOT;</p>
    <p>Build status: <span style='color: ${colorCode};'>${buildStatus}</span></p>"""

  emailext (
      mimeType: 'text/html',
      subject: subject,
      body: details,
      recipientProviders: [developers(), requestor()]
    )
}
