#!groovy

// this groovy script is executed by jenkins
node {

  environment {
    ANDROID_SDK_ROOT = '/var/lib/android-sdk'
  }


  // checkout code from scm
  stage('Checkout') {
    checkout scm
  }

  def version = ''
  def release = false

  // configure the deployer based on the version
  stage('Configure') {
    version = sh(returnStdout: true, script: "./gradlew properties -q | grep \"version:\" | awk '{print \$2}'", label: "Detecting project version.").trim()
    println "Version is: '${version}'"
    release = (! version.endsWith("-SNAPSHOT"))
  }

  // build the source code with gradle
  stage('Build') {
	 withCredentials([string(credentialsId: 'maptology-keystore-password', variable: 'PASSWD')]) {
     sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD clean build', label: "Building project.")
	 }
  }

  // deploy the maven publications to nexus
  stage ('Publish') {
    if (env.BRANCH_NAME == "master") {
  	 withCredentials([string(credentialsId: 'jenkins-nexus-password', variable: 'NEXUS')]) {
      withCredentials([string(credentialsId: 'maptology-keystore-password', variable: 'PASSWD')]) {
        sh(script: './gradlew -Djenkins.build.number=' + env.BUILD_NUMBER + ' -Dandroid.keystore.password=$PASSWD -Djenkins.nexus.password=$NEXUS publishAllPublicationsToMavenRepository', label: "Publishing project.")
      }
     }
    } else {
      echo "Skipping publication for non-master branch."
    }
  }

  // deploy the build output on the server
 stage ('Deploy') {
    if (env.BRANCH_NAME == "master" && release) {
      withCredentials([sshUserPrivateKey(credentialsId: "maptology-server-key", keyFileVariable: "KEYFILE")]) {
        sh 'scp -i $KEYFILE site-ear/build/libs/site-ear-' + version + '.ear wildfly@apps-pro.nes.uni-due.de:/opt/wildfly-21-maptology/standalone/deployments/maptology.ear'
        sh 'scp -i $KEYFILE android-app/build/outputs/apk/release/*.apk wildfly@apps-pro.nes.uni-due.de:/opt/android/maptology/'
      }
    } else {
      echo "Skipping deployment for non-master branch or non-release build."
    }
 }

}
