pipeline {
  agent {
    dockerfile true
  }
  stages {
    stage('build') {
      steps {
        sh './scripts/ci-codeartifact-login'
        sh 'npm ci'
        sh 'npm run build'
        sh 'npm run test'
      }
    }
    stage('CodeArtifact') {
      when { branch 'master' }
      steps {
        catchError {
          // Will get EPUBLISHCONFLICT if version already exists
          sh 'npm publish'
        }
      }
    }
    stage('Artifactory') {
      when { branch 'master' }
      environment {
        REPO="https://packages.internal.justin.tv/artifactory/api/npm"
      }
      steps {
        // Rename the package to the Twitch classic version: cdk-plugin-isengard
        sh "cat package.json | jq '.name = \"cdk-plugin-isengard\"' > tmp && mv tmp package.json"
        withCredentials([[$class: 'StringBinding', credentialsId: 'dta_tools_deploy', variable: 'PASSWORD']]) {
          sh 'curl -u dta_tools:$PASSWORD $REPO/auth > ~/.npmrc'
        }
        sh 'echo "email=dta@justin.tv" >> ~/.npmrc'
        sh 'echo "always-auth=true" >> ~/.npmrc'
        // Will get E403 if version already exists
        sh 'npm publish --registry $REPO/ip-npm'
      }
    }
  }
}
