#!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 {
    agent none

    options {
        disableConcurrentBuilds()
    }

    environment {
        GOPATH = "/home/jenkins/agent/workspace/go"
        REGION = "us-west-2"
        AWS_DEFAULT_REGION  = "us-west-2"
        GITHUB_BOT = credentials("github-sre-bot")
        GOPRIVATE="github.com/tidbcloud"
    }

    stages {
        stage('Release') {
            // release only applies on tags like 'release-v20200720' or 'release-v0.1.0'
            when {
                tag pattern: "release-v.+", comparator: "REGEXP"
            }
            environment {
                ENV = "prod"
                PROJECT = "prod"
                AWS_ROLE_ARN = credentials("dbaas-${env.ENV}-aws-role")
                GCR_REGISTRY = "gcr.io/dbaas-prod"
            }

            stages {
                stage('Build') {
                    agent {
                        kubernetes {
                            yaml pulumiPod
                            defaultContainer "main"
                            customWorkspace "/home/jenkins/agent/workspace/go/src/github.com/pingcap/dbaas"
                        }
                    }
                    steps {
                        sh '''
                        echo "machine github.com login ${GITHUB_BOT_USR} password ${GITHUB_BOT_PSW}" > ~/.netrc
                        IMAGE_TAG=${TAG_NAME} ./build.sh
                        '''
                    }
                }
                stage('Deploy') {
                    input {
                        message "Do you want to approve this release to production?"
                        ok "Yes, ship it!"
                        // operators who have permission to approve the deploy
                        submitter "dengshuan@pingcap.com,greg@pingcap.com"
                    }
                    agent {
                        kubernetes {
                            yaml pulumiPod
                            defaultContainer "main"
                            customWorkspace "/home/jenkins/agent/workspace/go/src/github.com/pingcap/dbaas"
                        }
                    }
                    environment {
                        KUBECONFIG = credentials("dbaas-${env.ENV}-kubeconfig")
                        PULUMI_CONFIG_PASSPHRASE = credentials("dbaas-${env.ENV}-pulumi-pwd")
                    }
                    steps {
                        sh '''
                        cd deploy/aws
                        npm install
                        pulumi login --cloud-url=s3://${ENV}-dbaas-pulumi-state
                        pulumi stack select ${PROJECT}
                        if [[ $(pulumi config get image_tag) != ${TAG_NAME}]]; then
                            echo "image_tag does not match git tag" && exit 1
                        fi
                        pulumi up --yes
                        '''
                    }
                    post {
                        unsuccessful {
                            script {
                                sendNotification("#dbaas-ci", 'FAILURE')
                            }
                        }
                        success {
                            script {
                                sendNotification("#dbaas-ci", 'SUCCESS')
                            }
                        }
                    }
                }
            }
        }
    }
}

def sendNotification(CHANNEL="#dbaas-ci", STATUS="SUCCESS") {
    def GIT_AUTHOR_NAME = sh(returnStdout: true, script: "git log -1 --pretty=format:'%an'").trim()
    def GIT_COMMIT_MSG = sh(returnStdout: true, script: "git log --oneline -n 1 --pretty=%B HEAD | head -n 1").trim()
    def slackmsg = "[<${env.RUN_DISPLAY_URL}|DBaaS ${env.ENV} release>] `${STATUS}`" + "\n" +
            "Commit: <https://github.com/tidbcloud/dbaas/commit/${env.GIT_COMMIT}|${GIT_COMMIT_MSG}>" + "\n" +
            "Tag: `${env.TAG_NAME}`, 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}"
}
