/*
 * The Jenkins job should be configured with the following properties:
 *
 * - Disable concurrent builds
 * - Parameters (all must be trimmed; all are strings):
 *   - RELEASE_TYPE
 *      defaultValue: auto
 *      description: Valid values are: auto, minor, snapshot.0, snapshot.1, edge. When "auto" is
 *                   specified, the type of the release will be determined based on the current date.
 *   - BACKEND_RELEASING_BRANCH
 *      defaultValue: refs/heads/master
 *      description: Branch of the backend to release
 *   - UI_RELEASING_BRANCH
 *      defaultValue: refs/heads/master
 *      description: Branch of the UI to release
 *   - BACKEND_GITHUB_URI
 *      defaultValue: git@github.com:kiali/kiali.git
 *      description: SSH Url of the kiali-backend GitHub repository
 *   - UI_GITHUB_URI
 *      defaultValue: git@github.com:kiali/kiali-ui.git
 *      description: SSH Url of the kiali-ui GitHub repository
 *   - DOCKER_NAME
 *      defaultValue: docker.io/kiali/kiali
 *      description: The name of the Docker repository to push the release
 *   - QUAY_NAME
 *      defaultValue: quay.io/kiali/kiali
 *      description: The name of the Quay repository to push the release
 *   - QUAY_OPERATOR_NAME
 *      defaultValue: quay.io/kiali/kiali-operator
 *      description: The name of the Quay repository to push the operator release
 *   - BACKEND_PULL_URI
 *      defaultValue: https://api.github.com/repos/kiali/kiali/pulls
 *      description: The URL of the GitHub API to use to create pull requests for the back-end (changes to prepare for next version)
 *   - UI_PULL_URI
 *      defaultValue: https://api.github.com/repos/kiali/kiali-ui/pulls
 *      description: The URL of the GitHub API to use to create pull requests for the UI (changes to prepare for next version)
 *   - NPM_DRY_RUN
 *      defaultValue: n
 *      description: Set to "y" if you want to make a "dry run" of the front-end release process
 *   - SKIP_UI_RELEASE
 *      defaultValue: n
 *      description: Set to 'y' if you don't want to release the UI
 *   - UI_VERSION
 *       defaultValue: ''
 *       description: If you are skipping UI release. Specify the UI version to package, or leave
 *                    unset to use the version present in the main Makefile (e.g. leave unset for patch releases)
 *   - NPM_CONFIG_REGISTRY
 *       defaultValue: ''
 *       description: Registry to use for fetching packages. This is not used for publishing releases.
 *                    Do not include the trailing slash.
 */

node('kiali-build') {
  def (backendForkUri, uiForkUri) = ['git@github.com:kiali-bot/kiali.git', 'git@github.com:kiali-bot/kiali-ui.git']
  def (backendDir, uiDir) = ['src/github.com/kiali/kiali', 'src/github.com/kiali/kiali-ui']
  def (backendMakefile, uiMakefile) = ['deploy/jenkins-ci/Makefile', 'Makefile.jenkins']
  def buildUi = params.SKIP_UI_RELEASE != "y"
  def dockerTag = ""
  def quayTag = ""

  try {
    cleanWs()
    stage('Checkout code') {
      checkout([
        $class: 'GitSCM',
        branches: [[name: params.BACKEND_RELEASING_BRANCH]],
        doGenerateSubmoduleConfigurations: false,
        extensions: [
          [$class: 'RelativeTargetDirectory', relativeTargetDir: backendDir]
        ],
        submoduleCfg: [],
        userRemoteConfigs: [[
          credentialsId: 'kiali-bot-gh-ssh',
          url: params.BACKEND_GITHUB_URI]]
      ])
      if ( buildUi ) {
        checkout([
          $class: 'GitSCM',
          branches: [[name: params.UI_RELEASING_BRANCH]],
          doGenerateSubmoduleConfigurations: false,
          extensions: [
            [$class: 'RelativeTargetDirectory', relativeTargetDir: uiDir]
          ],
          submoduleCfg: [],
          userRemoteConfigs: [[
            credentialsId: 'kiali-bot-gh-ssh',
            url: params.UI_GITHUB_URI]]
        ])

        sh "cd ${uiDir}; git config user.email 'kiali-dev@googlegroups.com'"
        sh "cd ${uiDir}; git config user.name 'kiali-bot'"
      }

      sh "cd ${backendDir}; git config user.email 'kiali-dev@googlegroups.com'"
      sh "cd ${backendDir}; git config user.name 'kiali-bot'"
    }

    // Determine release type if "auto" was specified
    def releaseType = "${params.RELEASE_TYPE}"
    if ( releaseType == "auto" ) {
      releaseType = sh(
        returnStdout: true,
        script: "${backendDir}/deploy/jenkins-ci/bin/determine-release-type.sh").trim()
    }
    echo "Resolved release type: ${releaseType}"

    withEnv(["PATH+TOOLS=${env.WORKSPACE}/${backendDir}/deploy/jenkins-ci/bin",
            "GOPATH=${env.WORKSPACE}",
            "BACKEND_FORK_URI=${backendForkUri}",
            "UI_FORK_URI=${uiForkUri}",
            "RELEASE_TYPE=${releaseType}"
    ]) {
      parallel backend: {
        withEnv(["GOPATH=${env.WORKSPACE}"]) {
          stage('Build backend') {
            sh "make -f ${backendMakefile} -C ${backendDir} backend-build-release"
          }
          stage('Test backend') {
            sh "make -f ${backendMakefile} -C ${backendDir} backend-test"
          }
        }
      }, ui: {
        stage('Build UI') {
          if ( buildUi ) {
            sh "make -f ${uiMakefile} -C ${uiDir} ui-fix-version ui-build"
          }
        }
        stage('Test UI') {
          if ( buildUi ) {
            sh "make -f ${uiMakefile} -C ${uiDir} ui-test"
          }
        }
      },
      failFast: true

      stage('Release kiali-ui to NPM') {
        if ( buildUi ) {
          withCredentials([string(credentialsId: 'kiali-npm', variable: 'NPM_TOKEN')]) {
            sh "make -f ${uiMakefile} -C ${uiDir} ui-npm-publish"
          }
        }
      }

      stage('Create release cut in front-end repo') {
        if ( buildUi ) {
          withCredentials([string(credentialsId: 'kiali-bot-gh-token', variable: 'GH_TOKEN')]) {
            sshagent(['kiali-bot-gh-ssh']) {
              sh "make -f ${uiMakefile} -C ${uiDir} ui-push-version-tag ui-prepare-next-version"
            }
          }
        }
      }

      stage('Release Kiali to Container Repositories') {
        withCredentials([usernamePassword(credentialsId: 'kiali-docker', passwordVariable: 'DOCKER_PASSWORD', usernameVariable: 'DOCKER_USER'), usernamePassword(credentialsId: 'kiali-quay', passwordVariable: 'QUAY_PASSWORD', usernameVariable: 'QUAY_USER')]) {
          sh "make -f ${backendMakefile} -C ${backendDir} backend-push-docker"
          dockerTag = sh(returnStdout: true, script: "sed -rn 's/^VERSION \\?= v(.*)/v\\1/p' ${backendDir}/Makefile").trim()
          quayTag = sh(returnStdout: true, script: "sed -rn 's/^VERSION \\?= v(.*)/v\\1/p' ${backendDir}/Makefile").trim()
        }
      }

      stage('Create release cut in back-end repo') {
        withCredentials([string(credentialsId: 'kiali-bot-gh-token', variable: 'GH_TOKEN')]) {
          sshagent(['kiali-bot-gh-ssh']) {
            sh "make -f ${backendMakefile} -C ${backendDir} backend-push-version-tag backend-prepare-next-version"
          }
        }
      }

     stage('Post Msg Bus Notification') {
       if ( releaseType == "minor" ) {
           build(job: 'kiali-release-notifier',
             parameters: [
               [$class: 'StringParameterValue', value: 'minor', name: 'RELEASE_TYPE'],
               [$class: 'StringParameterValue', value: "${params.DOCKER_NAME}", name: 'DOCKER_NAME'],
               [$class: 'StringParameterValue', value: "${params.QUAY_NAME}", name: 'QUAY_NAME'],
               [$class: 'StringParameterValue', value: dockerTag, name: 'DOCKER_TAG'],
               [$class: 'StringParameterValue', value: quayTag, name: 'QUAY_TAG']
             ], wait: false
           )
       }
     }
    }
  } finally {
    cleanWs()
  }
}

