#!groovy

import groovy.transform.Field

@Field
def pulumiPod = '''
apiVersion: v1
kind: Pod
spec:
  containers:
  - name:  main
    image: pulumi/pulumi:v3.4.0
    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
    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 pulumiPod
      defaultContainer "main"
    }
  }

  options {
    disableConcurrentBuilds()
  }
  environment {
    PULUMI_ACCESS_TOKEN = credentials("dbaas-pulumi-access-token")  // new pulumi access token
    PULUMI_CONFIG_PASSPHRASE = credentials("dbaas-dev-pulumi-pwd")
    GITHUB_BOT = credentials("github-sre-bot")
  }
  stages {
    stage('Dev') {
      environment {
        AWS_ROLE_ARN = credentials("dbaas-dev-aws-role")
      }
      when { branch 'main' }

      steps {
        withCredentials([usernamePassword(credentialsId: 'github-sre-bot',
                                          usernameVariable: 'GITHUB_APP',
                                          passwordVariable: 'GITHUB_ACCESS_TOKEN')]) {
          runPulumi("preview --diff", ".", "dev")
          runPulumi("up --yes", ".", "dev")
        }
      }
    }
  }
}

def runPulumi(SUB_COMMAND, DIR, STACK) {
    // unset KUBECONFIG to avoid creating resources without provider specified
    // unset HODSON_URL so that pulumi can detect the CI environment correctly
    sh """
    unset KUBECONFIG
    unset HUDSON_URL
    cd ${DIR}
    npm install
    npm update
    pulumi login https://api.pulumi.com
    pulumi stack select --create --secrets-provider=passphrase ${STACK}
    pulumi ${SUB_COMMAND}
    """
}