parameters {
    string(name: 'tagVersion', description: 'new version number for tag')
}

def makerelease() {
    try {
        stage('merge'){
            checkout([$class: 'GitSCM', branches: [[name: '*/release']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'LocalBranch', localBranch: "**"]], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '361885ba-9425-4230-950e-0af201d90547', url: 'https://git.auckland.dynabic.com/words-cloud/words-cloud-dart.git']]])
            sh "git config user.email 'jenkins.aspose@gmail.com'"
            sh "git config user.name 'jenkins'"
            sh "git checkout --merge release"
            sh "git reset --hard origin/release"
            sh "git merge --no-ff --allow-unrelated-histories origin/master"
            sh "git diff --name-status"
            sh 'git commit -am "Merged master branch to release" || exit 0'
            withCredentials([usernamePassword(credentialsId: '361885ba-9425-4230-950e-0af201d90547', passwordVariable: 'gitPass', usernameVariable: 'gitUsername')]) {
                sh "git push https://$gitUsername:$gitPass@git.auckland.dynabic.com/words-cloud/words-cloud-dart.git release"
            }
        }

        stage('tag'){
            checkout([$class: 'GitSCM', branches: [[name: '*/release']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'LocalBranch', localBranch: "**"]], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '361885ba-9425-4230-950e-0af201d90547', url: 'https://git.auckland.dynabic.com/words-cloud/words-cloud-dart.git']]])
            sh "git config user.email \"jenkins.aspose@gmail.com\""
            sh "git config user.name \"jenkins\""
            sh "git tag -a ${tagVersion} -m 'version ${tagVersion}' | exit 0"
            
            withCredentials([usernamePassword(credentialsId: '361885ba-9425-4230-950e-0af201d90547', passwordVariable: 'gitPass', usernameVariable: 'gitUsername')]) {
                sh "git push https://$gitUsername:$gitPass@git.auckland.dynabic.com/words-cloud/words-cloud-dart.git ${tagVersion}"
            }
        }
    } finally {
        deleteDir()
    }
}

node('words-linux') {
    cleanWs()
    makerelease()
}