pipeline {
    agent any
    environment {
        GITHUB_CREDS = credentials('GITHUB_CRED')
        RELEASE_BRANCH = "release-${env.BUILD_DATE}"
    }
    options {
        disableConcurrentBuilds()
        timeout(time: 15, unit: 'MINUTES')
    }
    stages {
        stage ('release branch and set version') {
            steps {
                sh "git config --global user.email \"jenkins@arkane.network\""
                sh "git config --global user.name \"Jenkins\""
                sh "git checkout -b ${RELEASE_BRANCH}"
                sh "npm version minor"
                withCredentials([usernamePassword(credentialsId: 'GITHUB_CRED', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                    sh 'git push https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ArkaneNetwork/arkane-connect.git HEAD:refs/heads/${RELEASE_BRANCH}'
                    sh 'git push https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ArkaneNetwork/arkane-connect.git --tags'
                }
            }
        }

        stage ('merge and publish') {
            environment {
                NPM_KEY = credentials('NPM_KEY')
            }
            steps {
                sh "git checkout master"
                sh "git merge --no-ff ${RELEASE_BRANCH}"
                sh "npm i"
                sh "npm run build-ts"
                sh "npm run build-js"
                sh "printf '//registry.npmjs.org/:_authToken=' > .npmrc && printf '${NPM_KEY}' >> .npmrc"
                sh 'npm publish'
                withCredentials([usernamePassword(credentialsId: 'GITHUB_CRED', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                    sh 'rm .npmrc'
                    sh 'git add .'
                    sh 'git commit --allow-empty -m "changes during ${RELEASE_BRANCH}"'
                    sh 'git push https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ArkaneNetwork/arkane-connect.git HEAD:refs/heads/master'
                    sh 'git push https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ArkaneNetwork/arkane-connect.git --tags'
                }
            }
        }

        stage ('backmerge to develop and increase dev version') {
            steps {
                sh "git checkout develop"
                sh "git merge --no-ff master"
                sh "npm version preminor --preid=develop --git-tag-version=false"
                sh 'git add .'
                sh 'git commit -m "bump develop version after ${RELEASE_BRANCH}"'
                withCredentials([usernamePassword(credentialsId: 'GITHUB_CRED', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                    sh 'git push https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ArkaneNetwork/arkane-connect.git HEAD:refs/heads/develop'
                }
            }
        }
    }

    post {
        always {
            cleanWs()
        }
    }
}
