pipeline {
  agent none
  
  options {
    timestamps()
    ansiColor('xterm')
  }

  environment {
    NPM_REPO="https://npm.pkgs.xarth.tv/"
  }

  stages {
    stage('install') {
      agent {
        docker {
          image 'docker.pkgs.xarth.tv/devtools/bionic/node12.10.0:latest'
        }
      }
      steps {
        sh 'yarn install'
        stash name: 'node_modules', includes: 'node_modules/**/*'
      }
    }

    stage('build_and_test') {
      agent {
        docker {
          image 'docker.pkgs.xarth.tv/devtools/bionic/node12.10.0:latest'
        }
      }
      steps {
        unstash name: 'node_modules'
        sh 'yarn build'
        sh 'yarn lint'
        sh 'yarn test'
      }
      post {
        always {
          junit 'output/junit/junit.xml'
          step([$class: 'CoberturaPublisher', coberturaReportFile: 'output/coverage/jest/cobertura-coverage.xml'])
        }
      }
    }
    
    stage('deploy') {
      agent {
        docker {
          image 'docker.pkgs.xarth.tv/devtools/bionic/node12.10.0:latest'
        }
      }
      when { branch 'master' }
      steps {
        sshagent(['devtools-ghe-user']) {
          checkout([$class: 'GitSCM', extensions: [[$class: 'LocalBranch', localBranch: "**"]], userRemoteConfigs: [[credentialsId: 'devtools-ghe-user', url: 'git@git.xarth.tv:flexo/flexo-cdk.git']]])
          unstash name: 'node_modules'
          withCredentials([[$class: 'StringBinding', credentialsId: 'dta_tools_deploy', variable: 'DTA_TOOLS_DEPLOY_PASS']]) {
              sh 'curl -udta_tools:$DTA_TOOLS_DEPLOY_PASS $NPM_REPO/auth > ~/.npmrc'
          }
          sh 'mkdir ~/.ssh && ssh-keyscan -t rsa git.xarth.tv >> ~/.ssh/known_hosts'
          sh 'yarn build'
          sh 'git config --global user.email "dta@twitch.tv"'
          sh 'git config --global user.name "Jenkins"'
          sh 'npx npm version minor'
          sh 'git push --tags'
          sh 'npx npm publish'
        }
      }  
    }
  }
}
