#!groovy

// this groovy script is executed by jenkins
node {


  def gradleInfo
  def server = Artifactory.server 'project.nes.uni-due.de'
  def gradleBuild = Artifactory.newGradleBuild()
  gradleBuild.tool = 'gradle-5.5.1'
  gradleBuild.usesPlugin = true

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


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

  def version = ''

  // 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}'"
    if (version.endsWith("-SNAPSHOT")) {
		println "Using internal-snapshots for publication."
      gradleBuild.deployer server: server, repo: 'internal-snapshots'
    } else {
		println "Using internal-releases for publication."
      gradleBuild.deployer server: server, repo: 'internal-releases'
    }
  }

  // build the source code with gradle
  stage('Build') {
	 withCredentials([string(credentialsId: 'maptology-keystore-password', variable: 'PASSWD')]) {
		 def switches = "-Djenkins.build.number=${env.BUILD_NUMBER} -Dandroid.keystore.password=${PASSWD}".toString()
    	 gradleInfo = gradleBuild.run buildFile: 'build.gradle', tasks: 'clean build', switches: switches
	 }
  }

  // deploy the maven publications to artifactory
  stage ('Publish') {
    if (env.BRANCH_NAME == "master") {
	 withCredentials([string(credentialsId: 'maptology-keystore-password', variable: 'PASSWD')]) {
		 def switches = "-Djenkins.build.number=${env.BUILD_NUMBER} -Dandroid.keystore.password=${PASSWD}".toString()
	     gradleInfo = gradleBuild.run buildFile: 'build.gradle', tasks: 'artifactoryPublish', switches: switches
	 }
    } else {
      echo "Skipping deployment for non-master branch."
    }
  }

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

}
