pipeline {
  agent any
  options {
    timestamps()
  }
  environment {
    CI='true'
    NODE_ENV='production'
    NODE_VER='8.11.1'
    DEPLOY_STAGE='false'
    DEPLOY_QA='false'
    TEST_ONLY='false'
    REACT_APP_TRIAGE_API_VERSION='v2'
  }
  stages {
    stage ('study-manager - Checkout') {
      steps {
        checkout scm
      }
    }

    stage ('study-manager - Build') {
      steps {
        configFileProvider([configFile(fileId: 'npmrc', targetLocation: '.npmrc'), configFile(fileId: 'study-manager-env-qa', targetLocation: '.env.qa'), configFile(fileId: 'study-manager-env-stage', targetLocation: '.env.stage'), configFile(fileId: 'study-manager-env-stage2', targetLocation: '.env.stage2'), configFile(fileId: 'study-manager-env-prod', targetLocation: '.env.prod')]) {}
        withCredentials([string(credentialsId: 'NPM_TOKEN', variable: 'NPM_TOKEN'), string(credentialsId: 'BROWSERSTACK_USERNAME', variable: 'BROWSERSTACK_USERNAME'), string(credentialsId: 'BROWSERSTACK_ACCESS_KEY', variable: 'BROWSERSTACK_ACESS_KEY'), string(credentialsId: 'INTEGRATION_TEST_AUTH_TOKEN', variable: 'INTEGRATION_TEST_AUTH_TOKEN')]) {
sh '''#!/usr/bin/env bash
set -e
. ~/.bash_profile
echo "yarn install --pure-lockfile"
NODE_ENV=production nvm exec $NODE_VER npm cache verify
NODE_ENV=development nvm exec $NODE_VER yarn install --pure-lockfile
echo "run test under src/"
NODE_ENV=development nvm exec $NODE_VER yarn run test
'''
        }
      }
    }
    stage ('study-manager - Build Release') {
      steps {
        withCredentials([string(credentialsId: 'NPM_TOKEN', variable: 'NPM_TOKEN')]) {
sh '''#!/usr/bin/env bash
set -e
. ~/.bash_profile
rm -rf srv/
rm -f .env

build () {
  VERSION="$(perl -ne '/"version": "([0-9.]+)"/ && print $1' package.json)+$(date +%s)"
  echo -e "\nREACT_APP_VERSION='${VERSION}'" >> .env
  rm -rf node_modules/
  NODE_ENV=production nvm exec $NODE_VER npm cache verify
  NODE_ENV=production nvm exec $NODE_VER yarn install --pure-lockfile
  NODE_ENV=production nvm exec $NODE_VER yarn run build
  mkdir srv/
  mv ./build srv/study-manager
  tar cf "study-manager_${VERSION}.tar" srv/
  fpm -s tar -t deb -n study-manager -v "$VERSION" "study-manager_${VERSION}.tar"
  /usr/local/bin/deb-s3 upload --bucket evi-studyv2-repo-stage -m $1 -v private --lock study-manager*.deb
}

if [ "${TEST_ONLY}" == true ]; then
  echo "run integration tests"
  NODE_ENV=development nvm exec $NODE_VER yarn run test:i:staging:activitypatterns
  exit $?
elif [ "${GIT_BRANCH}" == "master" ] || [ "${DEPLOY_QA}" == true ]; then
   echo "Building for QA"
   ln -s .env.qa .env
   build qa
elif [ "${GIT_BRANCH}" == "staging" ] || [ "${DEPLOY_STAGE}" == true ]; then
   echo "Building for staging"
   ln -s .env.stage .env
   build main
elif [ "${GIT_BRANCH}" == "production" ]; then
   echo "Building for production"
   ln -s .env.prod .env
   build prod
   ln -sf .env.stage2 .env
   build stage2
else
  echo "Not one of qa, staging or production, not building release."
  exit 0
fi
'''
        }
      }
    }
  }
  post {
    always {
      archiveArtifacts allowEmptyArchive: true, artifacts: '*.deb', caseSensitive: true, defaultExcludes: true, fingerprint: true, onlyIfSuccessful: true
      sh '''
        rm -f *.deb
        rm -f study-manager*.tar
      '''
    }
    success {
      setBuildStatus("Build complete", "SUCCESS");
    }
    failure {
      setBuildStatus("Build failed", "FAILURE");
      sendEmail();
    }
    aborted {
      setBuildStatus("Build failed", "FAILURE");
      sendEmail();
    }
  }
}
def getRepoURL() {
  sh "git config --get remote.origin.url > .git/remote-url"
  return readFile(".git/remote-url").trim()
}

def getCommitSha() {
  sh "git rev-parse HEAD > .git/current-commit"
  return readFile(".git/current-commit").trim()
}
void setBuildStatus(String message, String state) {
  repoUrl = getRepoURL()
  commitSha = getCommitSha()
  step([
      $class: "GitHubCommitStatusSetter",
      reposSource: [$class: "ManuallyEnteredRepositorySource", url: repoUrl],
      commitShaSource: [$class: "ManuallyEnteredShaSource", sha: commitSha],
      contextSource: [$class: "ManuallyEnteredCommitContextSource", context: "ci/jenkins/build-status"],
      errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
      statusResultSource: [ $class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]] ]
  ]);
}
void sendEmail() {
  step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: emailextrecipients([[$class: 'CulpritsRecipientProvider'], [$class: 'RequesterRecipientProvider']])]);
}
