#!/usr/bin/env groovy

@Library('wa3-fa-shared-library@node-16') _
import com.backbase.jenkins.Monorepo

registry = "https://registry.npmjs.org/"

String getPackageVersion() {
  nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
    return sh(
      returnStdout: true,
      script: "node -p \"require('./package.json').version\""
    ).trim();
  }
}

String getPackageName() {
  nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
    return sh(
      returnStdout: true,
      script: "node -p \"require('./package.json').name\""
    ).trim();
  }
}

pipeline {
  environment {
    PROJECT = 'FBB'
    REPO = 'backbase-schematics'
  }

	agent {
		kubernetes {
      inheritFrom 'chrome-pod-extra-resources-jdk11'
      yamlFile './chromePodExtraResource.yml'

		}
	}

  triggers {
    pollSCM('');
    bitbucketPush();
  }

  options {
    disableConcurrentBuilds()
    timeout(time: 3, unit: 'HOURS')
  }

  stages {
    stage('Install') {
      steps {
        script {
          nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
            sh 'npm ci';
          }
        }
      }
    }

    stage('Test') {
      steps {
        script {
          sh 'chmod +x ./scripts/output.sh';
          nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
            sh 'npm run test';
            sh './scripts/output.sh';
          }
          String gitDiff = sh(script: 'git diff ./output', returnStdout: true);
          if (gitDiff.length() > 0) {
            echo(gitDiff);
            error("Error: Output of the schematics does not match.");
          }
        }
      }
    }

    stage('Sonar Scan') {
      steps {
        runFeSonar()
      }
    }

    stage('Build') {
      steps {
        script {
          nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
          }
        }
      }
    }

    stage('Build docs') {
      steps {
        script {
          nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
            sh 'npm run build:readme'
            sh 'npm run build:docs'
          }
        }
      }
    }

    stage('Publish') {
      when {
        allOf {
          // Note: if changing branch from "master", also change tag from "latest" below.
          // We should only release "latest" tags from "master" branch.
          branch 'master';
          expression {
            !npmInfo.isPublished(getPackageName(), getPackageVersion(), registry)
          }
        }
      }
      steps {
        script {
          String newVersion = "v${getPackageVersion()}";
          sh "git tag -a -m 'Tagging $newVersion' '$newVersion'";
          sshagent(['3c6ce841-8358-436f-8dbd-fb6b22af9244']) {
            sh "git push --tags origin";
          }
        }
        withCredentials([string(credentialsId: 'public-registry-npm-token', variable: 'NPM_TOKEN')]) {
          script {
            Boolean isStableVersion = packageVersion.indexOf("-") < 0;
            String tag = (isStableVersion) ? "latest" : "beta";
            nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
              sh "NPM_TOKEN=$NPM_TOKEN npm publish --tag $tag --userconfig .npmrc-publish";
            }
          }
        }
      }
    }

    stage('Publish docs') {
      when {
        anyOf {
          branch 'master';
          changeRequest()
        }
      }
      steps {
        script {
          def isRelease = "${env.BRANCH_NAME}" == 'master';
          def awsCredentialsId = (isRelease) ? 'ce103ea8-5bf6-11eb-ae93-0242ac130002' : 'api_portal_fe_docs';
          def awsBucketName = (isRelease) ? 's3://api-portal-backbase' : 's3://backbase-api-portal';

          if (!isRelease) {
            println "For non-release build docs will be published to https://developer-staging.backbase.eu/";
          }

          nodejs(nodeJSInstallationName: Monorepo.NODE_INSTALLATION_NAME, configId: env.NPM_SETTINGS_ID) {
            withCredentials([[
              $class: 'UsernamePasswordMultiBinding',
              credentialsId: awsCredentialsId,
              usernameVariable: 'AWS_ACCESS_KEY_ID',
              passwordVariable: 'AWS_SECRET_ACCESS_KEY'
            ]]) {
              withEnv(["AWS_BUCKET=${awsBucketName}"]) {
                sh "npm run publish:docs .";
              }
            }
          }
        }
      }
    }
  }
}