def AGENT_LABEL = "NodeJS"

node("${AGENT_LABEL}") {
    stage('Prep') {
        checkout scm

       if(env.BRANCH_NAME.startsWith("v"))
        {
            // Versions should look like this: v2.3
            def version_number = env.BRANCH_NAME.substring(1);
            def major_version = version_number.substring(0, version_number.indexOf("."));
            def minor_version = version_number.substring(version_number.lastIndexOf('.') + 1);
            NEW_VERSION = "v" + major_version + "." + minor_version + "." + env.BUILD_NUMBER;
            currentBuild.displayName = NEW_VERSION
        }

        AWS_CRED_ID = "build-test-aws"

        withCredentials([[
            $class: 'AmazonWebServicesCredentialsBinding',
            credentialsId: "${AWS_CRED_ID}",
            accessKeyVariable: 'AWS_ACCESS_KEY_ID',
            secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
        ]]) {
            AWS_ACCESS_ID = env.AWS_ACCESS_KEY_ID
            AWS_SECRET_KEY = env.AWS_SECRET_ACCESS_KEY
        }

        withCredentials([usernamePassword(credentialsId: 'npm-public',
            usernameVariable: 'USERNAME', passwordVariable: 'TOKEN')]) {
            sh '''
                export NPM_TOKEN=$PASSWORD
            '''
            NPM_TOKEN = env.TOKEN
        }
    }
}

pipeline {
    agent { 
        node {
            label "${AGENT_LABEL}"
        }
    }
    options {
        timestamps()
        timeout(time: 1, unit: 'HOURS')
        skipStagesAfterUnstable()
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '10'))
    }
    environment {
        AWS_ACCESS_KEY_ID = "${AWS_ACCESS_ID}"
        AWS_SECRET_ACCESS_KEY = "${AWS_SECRET_KEY}"
        NPM_TOKEN = "${NPM_TOKEN}"
    }
    stages {
        stage('Create Tag') {
            when {
                    branch 'v*'
            }
            steps {
                sshagent(credentials: ['github-ssh']) {
                    sh """
                        git remote get-url --push origin \
                        | sed -e "s/https:\\/\\/github.com\\//git@github.com:/" \
                        | xargs git remote set-url --push origin
                        echo "Remotes:"
                        git remote -v
                        set +x
                        export GIT_SSH_COMMAND="ssh -oStrictHostKeyChecking=no"
                        git tag -a ${NEW_VERSION} -m "Release ${NEW_VERSION}"
                        git push origin ${NEW_VERSION}
                    """
                }
            }
        }
        stage('Build') {
            steps {
                sh "./build.sh"
            }
        }
        stage('Test') {
            steps {
                sh "./test.sh"
                //cobertura autoUpdateHealth: false, autoUpdateStability: false, coberturaReportFile: 'coverage/cobertura-coverage.xml', conditionalCoverageTargets: '70, 0, 0', failUnhealthy: false, failUnstable: false, lineCoverageTargets: '80, 0, 0', maxNumberOfBuilds: 0, methodCoverageTargets: '80, 0, 0', onlyStable: false, sourceEncoding: 'ASCII'
            }
        }
        stage('Publish') {
            when {
                anyOf {
                    branch 'v*'
                }
            }
            steps {
                sh "ls -ltra"
                sh "./publish.sh ${NEW_VERSION}"
            }
        }
    }
    post {
       failure {
            script {
                if (env.BRANCH_NAME == 'main' || env.BRANCH_NAME == 'master' || env.BRANCH_NAME.startsWith('v')) {
                    slackSend message: "❌ Ooops, `${env.JOB_NAME}` failed on build `#${env.BUILD_NUMBER}` 🥺 (<${env.BUILD_URL}|See Details...>)"
                }
            }
       }
       fixed {
            script {
                if (env.BRANCH_NAME == 'main' || env.BRANCH_NAME == 'master' || env.BRANCH_NAME.startsWith('v')) {
                    slackSend message: "✅ Yaaay, `${env.JOB_NAME}` fixed with build `#${env.BUILD_NUMBER}` 🏆 (<${env.BUILD_URL}|See Details...>)"
                }
            }
       }
    }
}
