pipeline {
  agent {
    node {
      label 'qa-executors'
    }
  }

  tools { nodejs "v12 LTS" }
  environment {
    imageName = "tracking-opt-in-demo"
    currentCommit = sh(returnStdout: true, script: "git log -n 1 --pretty=format:'%h'").trim()
    dockerRepoUrl = "${env.DOCKER_REPO_URL}"
    serviceName = "${imageName}-${currentCommit}"
    appHost = "${env.APP_HOST_PREFIX}${currentCommit}${env.APP_HOST_SUFFIX}"
  }

  stages {

    stage('dependencies') {
      steps {
        sh "yarn install --frozen-lockfile"
      }
    }

    stage('tests') {
      steps {
        sh "yarn test"
      }
    }

    stage('build app') {
      steps {
        sh "yarn clean"
        sh "yarn build"
      }
    }

    stage('start test container') {
      when {
        expression {
            return params.skipTests != true
        }
      }
      steps {
        sh "docker build --file release/demo-container/Dockerfile --tag ${imageName}:${currentCommit} ."
        sh "docker tag ${imageName}:${currentCommit} ${dockerRepoUrl}/${imageName}:${currentCommit}"
        sh "docker push ${dockerRepoUrl}/${imageName}:${currentCommit}"
        sh '''
            APP_HOST="${appHost}" \
            IMAGE="${dockerRepoUrl}/${imageName}:${currentCommit}" \
            INSTANCES=1 \
            NAMESPACE="$K8S_NAMESPACE" \
            SERVICE_NAME="${serviceName}" \
            node release/scripts/generate-k8s-yaml.js > release/k8s.yaml
        '''
        withDockerContainer(env.K8S_DEPLOYER) {
            sh "kubectl -n $K8S_NAMESPACE --context $K8S_CONTEXT apply -f release/k8s.yaml"
        }
      }
    }

    stage('BrowserStack') {
      when {
        expression {
            return params.skipTests != true
        }
      }
      steps {
        sh "BUILD_ID=${currentCommit} TEST_URL=${params.testUrl ?: "http://${appHost}"} yarn test:selenium"
      }
    }

    stage('release') {
      steps {
        sshagent(credentials: ["$CREDENTIAL_ID"]) {
          sh "git checkout ${params.branch}"
          sh "npm config set '//registry.npmjs.org/:_authToken' ${env.NPM_TOKEN}"
          sh "yarn version --new-version ${params.version}"
          sh "npm publish"
          sh "git push origin ${params.branch}"
          sh "git push origin --tags"

          slackSend (
            channel: '#adeng-release',
            color: 'good',
            failOnError: true,
            message: ":checkmark: new version of tracking-opt-in has been released to https://www.npmjs.com/package/@wikia/tracking-opt-in"
          )
        }
      }
    }
  }

  post {
    success {
      slackSend (
        channel: '#adeng-release',
        color: 'good',
        failOnError: true,
        message: ":checkmark: tracking-opt-in ${params.pipeline} on ${params.branch} <${env.BUILD_URL}|succeeded>"
      )
    }

    failure {
      slackSend (
        channel: '#adeng-release',
        color: 'warning',
        failOnError: true,
        message: ":warning: tracking-opt-in ${params.pipeline} on ${params.branch} <${env.BUILD_URL}|failed>"
      )
    }

    always {
      script {
        allure([includeProperties: false, jdk: '', properties: [], reportBuildPolicy: 'ALWAYS', results: [[path: 'reports/selenium/allure'], [path: 'reports/karma/allure']]])
      }

      junit allowEmptyResults: true, testResults: 'reports/karma/junit/*.xml'
      junit allowEmptyResults: true, testResults: 'reports/webdriver/junit/*.xml'
      publishHTML([
        allowMissing: true,
        alwaysLinkToLastBuild: false,
        keepAll: true,
        reportDir: 'reports/karma/coverage',
        reportFiles: 'index.html',
        reportName: 'Unit Test Code Coverage Report',
        reportTitles: ''
      ])
      /* withDockerContainer(env.K8S_DEPLOYER) {
        sh "kubectl -n $K8S_NAMESPACE --context $K8S_CONTEXT delete service,deployment,ingress -l app=${serviceName}"
      } */
    }
  }
}
