#!groovy

// default agent has golang, python, typescript, docker, aws and gcp environment configured
def agentPod = '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: main
    image: pulumi/pulumi:v2.15.3
    command:
    - cat
    tty: true
    env:
    - name: DOCKER_HOST
      value: tcp://localhost:2375
  - name: dind
    image: docker:18.09-dind
    securityContext:
      privileged: true
  restartPolicy: Never
'''

pipeline {
    agent {
        kubernetes {
            yaml agentPod
            defaultContainer "main"
            // TODO: change to your service
            customWorkspace "/home/jenkins/agent/workspace/go/src/github.com/tidbcloud/YOUR_SERVICE"
        }
    }

    environment {
        GOPATH = "/home/jenkins/agent/workspace/go"
        // ref: https://www.goproxy.io/docs/GOPRIVATE-env.html
        GOPRIVATE = "github.com/tidbcloud,github.com/pingcap/dbaas"
        // used to download our private go modules under the tidbcloud org
        GITHUB_BOT = credentials("github-sre-bot")
        // docker image url
        // TODO: change to your service
        BASE_IMG = "gcr.io/pingcap-public/YOUR_SERVICE"
    }

    stages {
        stage('Setup') {
            steps {
                sh '''
                # prepare permission to get private go packages
                echo "machine github.com login ${GITHUB_BOT_USR} password ${GITHUB_BOT_PSW}" > ~/.netrc
                # TODO: add your setup actions
                '''
            }
        }
        // 'Check' will always be executed when the job is triggered.
        // It is recommended to keep check reliable and fast since 'Check' will be executed for every PR by default.
        stage('Check') {
            steps {
                sh '''
                make verify
                # TODO: add your check actions
                '''
            }
        }
        stage('Build') {
            // 'Build' will not be executed when the job is triggered by PR
            when {
                not { changeRequest() }
            }
            steps {
                sh '''
                # configure gcr image push permissions
                gcloud auth configure-docker

                # build and push the service image
                # TAG_NAME   will be automatically set by Jenkins if the job is triggered by a tag push
                # GIT_COMMIT will be automatically set by Jenkins if the job is triggered by a commit
                IMG="${BASE_IMG}:${TAG_NAME:-$GIT_COMMIT}"
                make IMG=${IMG} docker-build docker-push
                echo "${IMG} pushed"
                '''
            }
            // TODO: uncomment notification and set your notification channel when needed
//            post {
//                unsuccessful {
//                    script {
//                        sendNotification("#YOUR_CHANNEL_HERE", "FAILED")
//                    }
//                }
//            }
        }
    }
}


def sendNotification(String CHANNEL, String STATUS) {
    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}|Build Config-Service Image>] `${STATUS}`" + "\n" +
            "Commit: <https://github.com/tidbcloud/infra-api/commit/${env.GIT_COMMIT}|${GIT_COMMIT_MSG}>" + '\n' +
            "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}"
}
