#!/usr/bin/env groovy

import java.util.regex.Matcher

void tryAddKnownHost(String hostUrl){
    // ssh-keygen -F ${hostUrl} will fail (in bash that means status code != 0) if ${hostUrl} is not yet a known host
    def statusCode = sh script:"ssh-keygen -F ${hostUrl}", returnStatus:true
    if(statusCode != 0){
        sh "mkdir -p ~/.ssh"
        sh "ssh-keyscan ${hostUrl} >> ~/.ssh/known_hosts"
    }
}

@NonCPS
String getShortVersion(String version) {
    def regexCheck = (version =~ /^(\d+)\.(\d+)\.\d+.*$/)
    def shortReleaseVersion = (regexCheck.size() > 0) ? "${regexCheck[0][1]}.${regexCheck[0][2]}" : ""
    return shortReleaseVersion
}

pipeline {
    agent {
        docker { image 'pegasyseng/pantheon-build:0.0.7-jdk11' }
    }
    parameters {
        string(name: 'BRANCH_NAME', defaultValue: 'master', description: '[MANDATORY] The name of the branch to create the release from')
        string(name: 'RELEASE_VERSION', defaultValue: 'x.y.z', description: '[MANDATORY] The version you are deploying')
        string(name: 'NEXT_VERSION', defaultValue: '', description: '[OPTIONAL] When empty: defaults to next patch version after current project version')
    }

    stages {
        stage('Release') {
            steps {
                sshagent(
                    credentials: ['pegasys-admin-github-ssh-private-key']
                ) {
                    withCredentials([
                        usernamePassword(
                            credentialsId: 'pegasys-bintray',
                            usernameVariable: 'BINTRAY_USER',
                            passwordVariable: 'BINTRAY_KEY'
                        )
                    ]) {
                        withEnv([
                            'GIT_COMMITTER_NAME="PegaSys Admin"',
                            'GIT_COMMITTER_EMAIL="pegasys.manager@gmail.com"',
                            'GIT_AUTHOR_NAME="PegaSys Admin"',
                            'GIT_AUTHOR_EMAIL="pegasys.manager@gmail.com"'
                        ]) {
                            tryAddKnownHost('github.com')

                             script{
                                  releaseVersion = ''
                                  if( params.RELEASE_VERSION?.trim() ){
                                      releaseVersion = "-Prelease.releaseVersion=${params.RELEASE_VERSION}"
                                  }

                                  nextVersion = ''
                                  if( params.NEXT_VERSION?.trim() ){
                                      nextVersion = "-Prelease.newVersion=${params.NEXT_VERSION}"
                                  }
                             }

                             sh "./gradlew release -Prelease.useAutomaticVersion=true -Prelease.branch=${params.BRANCH_NAME} ${releaseVersion} ${nextVersion}"
                        }
                    }
                }
            }
        }
        stage('Docker') {
            steps {
                script {

                    def docker_folder = 'docker'
                    def reports_folder = docker_folder + '/reports'
                    def releaseVersion = "${params.RELEASE_VERSION.trim()}"
                    def pantheon = "pegasyseng/pantheon:" + releaseVersion
                    def shortReleaseVersion = getShortVersion(releaseVersion)
                    def additionalTags = []

                    stage(stage_name + 'Build image') {
                        sh "echo Building docker image for release ${releaseVersion} with short version ${shortReleaseVersion}"
                        sh "./gradlew distDocker -x test -Prelease.releaseVersion=${releaseVersion} "
                    }

                    try {
                        stage(stage_name + 'Test image') {
                            sh "mkdir -p ${reports_folder}"
                            sh "cd ${docker_folder} && bash test.sh ${pantheon}"
                        }
                    } finally {
                        junit "${reports_folder}/*.xml"
                        sh "rm -rf ${reports_folder}"
                    }

                    stage(stage_name + 'Push image') {

                        def dockerImage = docker.image(pantheon)
                        docker.withRegistry('https://registry.hub.docker.com', 'dockerhub-pegasysengci') {
                            dockerImage.push()

                            // if this is a stable release add extra docker image tags
                            if (!releaseVersion.contains('-')) {
                                additionalTags.add('latest')
                                if (shortReleaseVersion != "") {
                                    additionalTags.add(shortReleaseVersion)
                                }
                            }
                            additionalTags.add('develop')

                            additionalTags.each { tag ->
                                dockerImage.push tag.trim()
                            }

                        }

                    }

                }

            }
        }
    }
}

