// vi:ft=groovy
@Library('finapi-build-library@develop')
import io.finapi.build.config.BuildConfig
import io.finapi.build.BuildLibrary

BuildConfig pipelineConfig = new BuildConfig()
pipelineConfig.useGithub = true
pipelineConfig.artifactory.repository = "di"
pipelineConfig.artifactory.skipSnapshotForRelease = true
pipelineConfig.artifactory.defaultTargetPrefix = "/io/finapi/r2wc"
pipelineConfig.artifactory.collateralSourceFiles = [
        'MIGRATION.md',
        'README.md',
        'devops/*'
]
pipelineConfig.projectName = "r2wc"
pipelineConfig.job.remoteAppName = "r2wc"

pipelineConfig.git.branchForSnapshot = "develop"
pipelineConfig.git.branchForReleases = "master"

pipelineConfig.npm.useJunit = false

BuildLibrary buildLibrary = new BuildLibrary(this, pipelineConfig)

def isRelease() { return env.BRANCH_NAME == 'master' }
def isPrerelease() { return env.BRANCH_NAME == 'develop' }

pipeline {
  options {
    buildDiscarder(logRotator(numToKeepStr: '5', artifactNumToKeepStr: '1'))
  }

  agent {
    label 'ec2-slave'
  }

  tools {
    nodejs "nodejs-20"
  }

  environment {
    NODE_OPTIONS = '--max_old_space_size=8192'
  }

  stages {
    stage('Initialize') {
      steps {
        script {
          env.committer       = sh(script: "git show -s --pretty=%an", returnStdout: true).trim()
          env.changesetShort  = sh(script: "git rev-parse --short HEAD", returnStdout: true).trim()
          env.changesetLong   = sh(script: "git rev-parse HEAD", returnStdout: true).trim()
          env.commitMessage   = sh(script: "git log -1 --pretty=%B", returnStdout: true).trim()

          buildLibrary.init()
          buildLibrary.tasks.job.terminateOutdatedJobs.run()
          buildLibrary.tasks.git.tagVersion.run()
        }
      }
    }

    // Builds the two publishable packages (r2wc-component and r2wc-vite)
    // via `npm run build:all`.
    stage('Build') { steps { script {
      buildLibrary.tasks.npm.build.run()
    } } }

    stage('Test') { steps { script {
      buildLibrary.tasks.npm.test.run()
    } } }

    // Publishes the two workspace packages to the internal npm registry via
    // `npm run publish:all` (publishConfig in each package.json pins the
    // target registry).
    stage('Release NPM') { steps { script {
      buildLibrary.tasks.npm.publish.run()
    } } }

    stage('Upload Collaterals') { steps { script {
      buildLibrary.tasks.artifactory.createAndPushCollaterals.run()
    } } }
  }

  post {
    unsuccessful {
      script {
        if (isPrerelease() || isRelease()) {
          slackSend(
            channel: '#proj-widget-library',
            color: 'danger',
            message: ":test_tube::right_arrow::globe_with_meridians: <${env.BUILD_URL}|${env.JOB_NAME} - build #${env.BUILD_NUMBER}> failed :sob:\n" +
              "• committer: ${env.committer}\n" +
              "• changeset: ${env.changesetShort}"
          )
        }
      }
    }

    fixed {
      script {
        if (isPrerelease() || isRelease()) {
          slackSend(
            channel: '#proj-widget-library',
            color: 'good',
            message: ":test_tube::right_arrow::globe_with_meridians: <${env.BUILD_URL}|${env.JOB_NAME} - build #${env.BUILD_NUMBER}> is fixed again.\nGood job ${env.committer}! :thumbsup:"
          )
        }
      }
    }

    success {
      script {
        if (isPrerelease() || isRelease()) {
          releaseIcon = isPrerelease() ? ":airplane:" : ":rocket:"
          slackSend(
            channel: '#proj-widget-library',
            color: 'good',
            message: ":test_tube::right_arrow::globe_with_meridians: r2wc ${buildLibrary.getConfig().states.buildVersion} released ${releaseIcon}\n" +
              "• ${env.commitMessage}\n" +
              "• <${env.BUILD_URL}|${env.JOB_NAME} - build #${env.BUILD_NUMBER}>"
          )
        }
      }
    }
  }
}
