#!groovy
import groovy.transform.Field

@Field
def pulumiPod = '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: main
    image: gcr.io/pingcap-public/third-party/pulumi:v2.15.3-go-v1.17.6
    command:
    - cat
    tty: true
    resources:
      requests:
        memory: "2000Mi"
        cpu: 2000m
      limits:
        memory: "4000Mi"
        cpu: 4000m
    env:
    - name: DOCKER_HOST
      value: tcp://localhost:2375
    - name: AWS_WEB_IDENTITY_TOKEN_FILE
      value: /identity/token
    volumeMounts:
    - mountPath: /identity
      name: identity
  - name: dind
    image: docker:18.09-dind
    securityContext:
      privileged: true
  - name: auth
    image: gcr.io/pingcap-gardener/jenkins/gcp-web-identity:20201201
    env:
    - name: AWS_WEB_IDENTITY_TOKEN_FILE
      value: /identity/token
    volumeMounts:
    - mountPath: /identity
      name: identity
  volumes:
  - emptyDir: {}
    name: identity
  restartPolicy: Never
'''

pipeline {
    parameters {
        string(name: 'INTEGRATION_SUITE', defaultValue: 'stability', description: 'the suite to run for integration test')
        string(name: 'PROJECT', defaultValue: 'stability', description: 'the dbaas central project to run test')
        string(name: 'PROVIDER', defaultValue: 'aws', description: 'the cloud provider to run test')
    }

    options {
        disableConcurrentBuilds()
    }

    agent {
        kubernetes {
            yaml pulumiPod
            defaultContainer "main"
            customWorkspace "/home/jenkins/agent/workspace/go/src/github.com/pingcap/dbaas"
        }
    }

    environment {
        GOPATH = "/home/jenkins/agent/workspace/go"
        PROVIDER = "${params.PROVIDER}"
        PROJECT = "${params.PROJECT}"
        SUITE = "${params.INTEGRATION_SUITE}"
        GINKGO_NODES = 1
        STAGE = "stability"
        ENV = "stability"
        REGION = "us-west-2"
        AWS_DEFAULT_REGION = "us-west-2"
        AWS_ROLE_ARN = credentials("dbaas-${env.STAGE}-aws-role")
        KUBECONFIG = credentials("dbaas-${env.STAGE}-kubeconfig")
        IMAGE_TAG = sh(returnStdout: true, script: "git rev-parse HEAD").trim()
        GIT_COMMIT_MSG = sh(returnStdout: true, script: "git log --oneline -n 1 --pretty=%B HEAD | head -n 1").trim()
    }

    stages {
        stage('Deploy') {
            environment {
                PULUMI_CONFIG_PASSPHRASE = credentials("dbaas-${env.STAGE}-pulumi-pwd")
            }
            steps {
                sh './hack/prepare-e2e.sh'
            }
        }
        stage('Run') {
            environment {
                AUTH0_CLIENT_ID = credentials("dbaas-auth0-client-id")
                AUTH0_CLIENT_SECRET = credentials("dbaas-auth0-client-secret")
            }
            steps {
                runTest()
            }
            post {
                unsuccessful {
                    script {
                        sendNotification("#dbaas-ci", 'FAILURE')
                    }
                }
            }
        }
    }
}

def runTest() {
    def ARTIFACTS = "${env.WORKSPACE}/artifacts"
    def builds = [:]
    if (env.PROVIDER == "all" || env.PROVIDER == "aws") {
        builds["AWS"] = {
            test("./hack/e2e.sh aws us-west-2", "${ARTIFACTS}/aws")
        }
    }

    if (env.PROVIDER == "all" || env.PROVIDER == "gcp") {
        builds["GCP"] = {
            test('./hack/e2e.sh gcp us-west1', "${ARTIFACTS}/gcp")
        }
    }
    builds.failFast = false
    parallel builds
}

def test(SHELL_CODE, ARTIFACTS) {
    sh """#!/bin/bash
    export REPORT_DIR=${ARTIFACTS}
    ${SHELL_CODE}
    """
    dir("${ARTIFACTS}") {
        archiveArtifacts artifacts: "**", allowEmptyArchive: true
        junit testResults: "*.xml", allowEmptyResults: true
    }
}

def sendNotification(CHANNEL="#dbaas-ci", STATUS="SUCCESS") {
    def GIT_AUTHOR_NAME = sh(returnStdout: true, script: "git log -1 --pretty=format:'%an'").trim()
    def slackmsg = "[<${env.RUN_DISPLAY_URL}|${env.JOB_NAME}>] `${STATUS}`" + "\n" +
            "Commit: <https://github.com/tidbcloud/dbaas/commit/${env.GIT_COMMIT}|${env.GIT_COMMIT_MSG}>" + "\n" +
            "Branch: `${env.GIT_BRANCH}`, Authored by: `${GIT_AUTHOR_NAME}`"
    def COLOR = 'good'
    if (STATUS != "SUCCESS") {
        COLOR = 'danger'
    }
    slackSend channel: CHANNEL, color: COLOR, teamDomain: 'pingcap', tokenCredentialId: 'slack-pingcap-token', message: "${slackmsg}"
}
