#!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:v3.3.1
    command:
    - cat
    tty: true
    resources:
      requests:
        memory: "2000Mi"
        cpu: 1000m
      limits:
        memory: "4000Mi"
        cpu: 1000m
    env:
    - name: AWS_WEB_IDENTITY_TOKEN_FILE
      value: /identity/token
    - name: DOCKER_HOST
      value: tcp://localhost:2375
    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 {
        kubernetes {
            yaml agentPod
            defaultContainer "main"
            customWorkspace "/home/jenkins/agent/workspace/go/src/github.com/tidbcloud/cost-provider"
        }
    }

    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")
        REGION = "us-west-2"
    }

    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
                '''
            }
        }
        stage('Release') {
            // release only applies on tags like 'release-v20200720' or 'release-v0.1.0'
            when {
                buildingTag()
            }
            environment {
                ENV = "prod"
                PROJECT = "prod"
                AWS_ROLE_ARN = credentials("dbaas-${env.ENV}-aws-role")
                AWS_DEFAULT_REGION = "us-west-2"
            }
            steps {
                sh '''#!/bin/bash
                make build

                # determine the image tag
                IMAGE_TAG=$(echo $TAG_NAME)

                IMAGES=(provider-cost-server)

                # push images to GCR
                GCR_REG="gcr.io/dbaas-prod/dbaas/prod"
                gcloud auth configure-docker
                for IMAGE_NAME in ${IMAGES[@]}; do
                    GCR_IMAGE="${GCR_REG}/${IMAGE_NAME}:${IMAGE_TAG}"
                    docker tag ${IMAGE_NAME}:local ${GCR_IMAGE}
                    docker push ${GCR_IMAGE}
                done;

                # push images to ECR
                ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
                for IMAGE_NAME in ${IMAGES[@]}; do
                    ECR_REPO="dbaas/prod/${IMAGE_NAME}"
                    ECR_REG="${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com"
                    if ! aws ecr describe-repositories --repository-name ${ECR_REPO} >/dev/null 2>&1
                    then
                        aws ecr create-repository --repository-name ${ECR_REPO}
                    fi
                    aws ecr get-login-password --region ${REGION} | docker login --username AWS --password-stdin ${ECR_REG}

                    ECR_IMAGE="${ECR_REG}/${ECR_REPO}:${IMAGE_TAG}"
                    docker tag ${IMAGE_NAME}:local ${ECR_IMAGE}
                    docker push ${ECR_IMAGE}
                done;

                trap "docker logout https://${ECR_REG}" EXIT
                '''
            }
            post {
                unsuccessful {
                    script {
                        sendNotification("#dbaas-infra-ci", "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}|Pushing Cost Provider Image to Prod Registry>] `${STATUS}`" + "\n" +
            "Commit: <https://github.com/tidbcloud/cost-provider/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}"
}
