pipeline {
  agent {
    node {
      label 'SCALE-Build'
    }
  }
  environment {
    BDIR = "/root/truenas-build"
    FIPS="1"
  }
  stages {
    stage('SCM') {
      steps {
        sh '[ -d "${BDIR}" ] || git clone --depth=1 https://github.com/truenas/truenas-build ${BDIR}'
        sh 'cd ${BDIR} && git reset --hard && git pull'
      }
    }
    stage('Checkout') {
      steps {
        sh 'cd ${BDIR} && env FORCE_CLEANUP_WITH_EPOCH_CHANGE=y make checkout'
        script {
          withCredentials([string(credentialsId: 'ce73d801-9cb5-41ea-814e-a416fa193afe', variable: 'ID')]) {
            sh 'cd conf && touch secrets.yaml'
            writeFile(file: "conf/secrets.yaml", text: ID)
          }
        }
      }
    }
    stage('Packages') {
      steps {
        sh 'cd ${BDIR} && make packages'
      }
    }
    stage('Update') {
      steps {
        sh 'cd ${BDIR} && make update'
      }
    }
    stage('ISO') {
      steps {
        sh 'cd ${BDIR} && make iso'
      }
    }
  }
  post {
    success {
      sh 'rm -rf artifacts || true'
      sh 'mkdir -p artifacts/logs'
      sh 'mv ${BDIR}/tmp/release/* artifacts/'
      sh 'cp -r ${BDIR}/logs/* artifacts/logs/'
      sh 'mkdir -p artifacts/packages'
      sh 'cp ${BDIR}/tmp/pkgdir/* artifacts/packages/'
      archiveArtifacts artifacts: 'artifacts/**', fingerprint: false
    }
    failure {
      sh 'rm -rf artifacts || true'
      sh 'mkdir -p artifacts/logs'
      sh 'cp -r ${BDIR}/logs/* artifacts/logs/'
      archiveArtifacts artifacts: 'artifacts/**', fingerprint: false
      mail bcc: '', body: "<b>Jenkins: TrueNAS SCALE Build Failure</b><br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL build: ${env.BUILD_URL}", cc: '', charset: 'UTF-8', from: '', mimeType: 'text/html', replyTo: '', subject: "ERROR CI: Project name -> ${env.JOB_NAME}", to: "rmesta@ixsystems.com,william@ixsystems.com";
    }
    always {
      sh 'rm -f conf/secrets.yaml'
    }
  }
}
