#!groovy

import groovy.transform.Field

@Field
def agentPod = '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: main
    image: pulumi/pulumi:v2.16.2
    command:
    - cat
    tty: true
    env:
    - name: AWS_WEB_IDENTITY_TOKEN_FILE
      value: /identity/token
    volumeMounts:
    - mountPath: /identity
      name: identity
  - 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{
        kubernetes {
            yaml agentPod
            defaultContainer "main"
            customWorkspace "/home/jenkins/agent/workspace/go/src/github.com/tidbcloud/appconfigs"
        }
    }
    options {
        disableConcurrentBuilds()
    }
    environment {
        GOPATH = "/home/jenkins/agent/workspace/go"
    }
    stages {
        stage('Locate') {
            steps {
                script {
                    def matcher = env.GIT_BRANCH=~/personal\/(.*)/
                    if (matcher.matches()) {
                        env.NAMESPACE = matcher.group(1)
                        env.STAGE = 'dev'
                    } else {
                        env.STAGE = env.GIT_BRANCH
                        // dev env use 'nightly' namespace
                        if (env.GIT_BRANCH=~/dev/) {
                            env.NAMESPACE = 'nightly'
                        } else {
                            env.NAMESPACE = env.GIT_BRANCH
                        }
                    }
                }
            }
        }
        stage('Deliver') {
            environment {
                KUBECONFIG = credentials("dbaas-${STAGE}-kubeconfig")
                AWS_ROLE_ARN = credentials("dbaas-${STAGE}-aws-role")
                GIT_COMMIT_MSG = sh(returnStdout: true, script: "git log --oneline -n 1 --pretty=%B HEAD | head -n 1").trim()
            }
            steps {
                sh '''
                ./apply.sh
                # remove this duplication when migration is done
                if [ "${NAMESPACE}" = "nightly" ]; then
                    NAMESPACE=nightly-ms ./apply.sh
                fi
                '''
            }
            post {
                unsuccessful {
                    script {
                        sendNotification('FAILURE')
                    }
                }
                success {
                    script {
                        sendNotification('SUCCESS')
                    }
                }
            }
        }
    }
}

def sendNotification(STATUS="SUCCESS") {
    if (env.STAGE == 'dev') {
        return
    }
    def WEBHOOK = 'https://open.feishu.cn/open-apis/bot/v2/hook/f269cb02-8c7a-49ef-ada6-9cf1816902d8'
    def WEBHOOK_NEW = 'https://open.feishu.cn/open-apis/bot/v2/hook/fae69551-940e-4ce6-b4ef-e022e9cf7b5e'
    def GIT_AUTHOR_NAME = sh(returnStdout: true, script: "git log -1 --pretty=format:'%an'").trim()
    def DATA = """
{
    "msg_type": "post",
    "content": {
        "post": {
            "zh_cn": {
                "title": "Update app config in [${STAGE}]: ${STATUS}",
                "content": [
                    [{
                        "tag": "text",
                        "text": "Commit: "
                    },
                    {
                        "tag": "a",
                        "text": "${env.GIT_COMMIT_MSG}",
                        "href": "https://github.com/tidbcloud/oneconfig/commit/${env.GIT_COMMIT}"
                    }],[{
                        "tag": "text",
                        "text": "Branch: ${env.GIT_BRANCH}, Authored by: ${GIT_AUTHOR_NAME}"
                    }]
                ]
            }
        }
    }
}
"""
    sh "curl -X POST -H 'Content-Type: application/json' -d '${DATA.replaceAll("[\r\n]+", " ")}' ${WEBHOOK}"
    sh "curl -X POST -H 'Content-Type: application/json' -d '${DATA.replaceAll("[\r\n]+", " ")}' ${WEBHOOK_NEW}"
}
