def gcloudProject = "smartmate-io"
def appName = "sm2"
def svcName = "schemas"
def chartMuseumUrl = "https://chartmuseum.apps.smartmate.io"
def imageRepo = "gcr.io/${gcloudProject}/${appName}"

pipeline {
  agent {
    kubernetes {
      label "sm2-schemas-builder"
      cloud "kubernetes"
      defaultContainer "jnlp"
      yamlFile "k8s/builderPod.yaml"
    }
  }
  options {
    buildDiscarder(logRotator(numToKeepStr: '5', artifactNumToKeepStr: '20', daysToKeepStr: '20'))
    timeout(time: 20, unit: 'MINUTES')
  }
  environment {
    SMARTMATE_QA_USER_ID = "U0NH7DPTQ" //QA Smartmate: Rodrigo Salazar
    NPM_PASSWORD = credentials("smartmate-npm-password")
    GIPHY_CREDENTIALS = credentials("giphy-api-secret-key")
    GCLOUD_SA = credentials("gcloud-access-service-account")
    KUBECTL_PRODUCTION = "--kubeconfig=/home/production/kubeconfig"
    LAST_AUTHOR = sh ( script : "git log -1 --pretty=format:'%an'", returnStdout:true)
  }
  stages {
    stage('Running Unit Tests') {
      when { not { environment name: 'LAST_AUTHOR', value: 'Jenkins' } }
      steps {
        container("node") {
          withBitbucketRepo(credentialId: "jenkins") {
            sh "git config --global url.'git@bitbucket.org:'.insteadOf 'https://bitbucket.org/'"
            sh "rm -rf node_modules"
            sh "yarn --frozen-lockfile && yarn coverage"
          }
        }
      }
      post {
        always {
          junit "test-report.xml"
          publishHTML(target: [allowMissing: false, alwaysLinkToLastBuild: false, keepAll: false, reportDir: 'coverage/lcov-report', reportFiles: 'index.html', reportName: 'Coverage', reportTitles: ''])
        }
      }
    }
    stage("Building and Uploading Image ") {
      when { branch 'master' }
      steps {
        container("gcloud") {
          sh "gcloud auth activate-service-account jenkins-operations@smartmate-io.iam.gserviceaccount.com --key-file=${GCLOUD_SA} --project=${gcloudProject}"
          sh "gcloud builds submit --tag ${imageRepo}/${svcName}:${env.BUILD_NUMBER} ."
          sh "gcloud container images add-tag ${imageRepo}/${svcName}:${env.BUILD_NUMBER} ${imageRepo}/${svcName}:latest"
        }
      }
    }
    stage('Publishing Schemas') {
      when { branch 'master' }
      steps {
        container("helm") {
          sh "sed -i -e \"s|\\(tag:\\).*|\\1 ${env.BUILD_NUMBER}|\" helm/values.yaml"
          sh "helm repo add ${appName} ${chartMuseumUrl}"
          sh "helm repo update"
          sh "helm ${KUBECTL_PRODUCTION} upgrade sm2-schemas --install ./helm --namespace=production"
        }
      }
    }
    stage('Publishing to npmjs.org') {
      when { branch 'master'
        not { environment name: 'LAST_AUTHOR', value: 'Jenkins' }
      }
      steps {
        script {
          container("node") {
            sh "npm install -g npm-cli-login publish"
            sh "npm-cli-login -u smartmate -p \"${NPM_PASSWORD}\" -e smartmate@smartmate.io -s @smartmate"
            def gitUrl = 'git@bitbucket.org:devsu/sm2-schemas.git'
            withBitbucketRepo(gitUrl: gitUrl, credentialId: 'jenkins', branch: "master") {
              sh "npm version patch"
              sh "npm publish"
              sh "git push origin master"
            }
          }
        }
      }
    }
  }
  post {
    always {
      script {
        if (env.CHANGE_TITLE != null) {
          if (env.CHANGE_TITLE.toUpperCase().matches(".*\\bRAPI\\b.*")) {
            sendSlackNotification action: "randomGIF", workspace: "devsu", channel: "#smartmate-deployments", conditionalBranch: "${env.BRANCH_NAME}", messageToSend: "A new *RAPI* implementation has begun ${env.GIT_URL_1}", giphyApiKey: "${GIPHY_CREDENTIALS}", giphyTag: "Happy"
          }
        }
      }
      sendSlackNotification workspace: 'devsu', channel: '#smartmate-deployments'
    }
  }
}
