#!groovy

// Required Jenkins plugins:
// https://wiki.jenkins-ci.org/display/JENKINS/Timestamper
// https://wiki.jenkins-ci.org/display/JENKINS/Static+Code+Analysis+Plug-ins
// https://wiki.jenkins-ci.org/display/JENKINS/Checkstyle+Plugin ?
// https://wiki.jenkins-ci.org/display/JENKINS/FindBugs+Plugin
// https://wiki.jenkins-ci.org/display/JENKINS/PMD+Plugin ?
// https://wiki.jenkins-ci.org/display/JENKINS/DRY+Plugin ?
// https://wiki.jenkins-ci.org/display/JENKINS/Task+Scanner+Plugin
// https://wiki.jenkins-ci.org/display/JENKINS/Javadoc+Plugin
// https://wiki.jenkins-ci.org/display/JENKINS/JaCoCo+Plugin ?


init()	  

def branch_name
def branch_name_base
def build_number
def build_url
def git_commit
def job_name
def tag
def version
def build_type
def display_name

def init() {

  // Keep the 5 most recent builds
  properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', numToKeepStr: '5']]])

  build_number = env.BUILD_NUMBER
  build_url = env.BUILD_URL
  job_name = "${env.JOB_NAME}"
  branch_name = env.BRANCH_NAME
  branch_name_docker = branch_name.replaceAll(/\//,'.')
  persist = "/var/lib/jenkins/PERSIST/${branch_name_docker}"

  // execute the branch type specific pipeline code
  try {
    
    if (branch_name.indexOf('release/')==0) build_type='release'
    if (branch_name.indexOf('feature/')==0) build_type='feature'
    if (branch_name.indexOf('develop')==0) build_type='develop'
    if (branch_name.indexOf('hotfix')==0) build_type='hotfix'
    if (branch_name.indexOf('bugfix')==0) build_type='bugfix'
    if (branch_name.indexOf('master')==0) build_type='master'

    // common pipeline elements
    node('master') {
          Initialize()
          SetVersion(build_type)
          print_vars() // after SetVersion - all variables now defined
          set_result('INPROGRESS')
          Build() // builds database via flyway migration
    }
    
   if (branch_name.indexOf('develop')==0) {
      node('master') {
            Deploy();
      }
    } else if (branch_name.indexOf('release/')==0) {
      node('master') {
            Deploy();
      }
    }

    node('master') {
          set_result('SUCCESS')
    }

  } catch (err) {
    node() {
          set_result('FAILURE')
    }
    throw err
  } 
}

def Build() {
  stage ('build') {
    mvn "install -DskipTests=true -Dbuild.revision=${git_commit}"
    step([$class: 'ArtifactArchiver', artifacts: '**/target/*.jar', fingerprint: true])
  }
}

def Initialize() {
  stage ('initialize') {
    
    // get new code
    checkout scm
    
    git_commit = getSha1()
  }
}

def Deploy() {
  stage ('deploy') {
    mvn "deploy -DskipTests=true -Dbuild.number=${build_number} -Dbuild.revision=${git_commit}"
  }
}

def getSha1() {
  sha1 = sh(script: 'git rev-parse HEAD', returnStdout: true).trim()
  echo "sha1 is ${sha1}"
  return sha1
}

def mvn(args) {
  withMaven(
    maven: 'maven-3.9.4',
    globalMavenSettingsConfig: 'locusworks-settings'
  ) {
  
  	sh "mvn ${args}"
  
  }
}

def mvn_initial(args) {
  mvn(args)
}

def set_result(status) {
  if ( status == 'SUCCESS' ) {
    currentBuild.result = status
    notify_bitbucket('SUCCESSFUL')
  } else if ( status == 'FAILURE' ) {
    currentBuild.result = status
    notify_bitbucket('FAILED')
  } else if ( status == 'INPROGRESS' ) {
    notify_bitbucket('INPROGRESS')
  } else {
    error ("unknown status")
  }

  // save in persistence file for access the status page
  // make sure the directory exists first
  sh "mkdir -p $persist && echo $status > $persist/build.result"
}

def notify_bitbucket(state) {
}

def print_vars() {
  echo "build_number = ${build_number}"
  echo "build_url = ${build_url}"
  echo "job_name = ${job_name}"
  echo "branch_name = ${branch_name}"
  echo "branch_name_base = ${branch_name_base}"
  echo "build_type = ${build_type}"
  echo "display_name = ${currentBuild.displayName}"
  echo "version = ${version}"
  echo "git_commit = ${git_commit}"

}

def SetVersion( v ) {
  stage ('set version') {
    echo "set version ${v}"
    branch_name_base = (branch_name =~ /([^\/]+$)/)[0][0]
    if ( v == 'release' ) {
      // for release branches, where the branch is named "release/1.2.3",
      // derive the version and display name derive from the numeric suffix and append the build number
      // 3.2.1.100
      version = branch_name_base + "." + build_number + "-RELEASE";
      //version = branch_name.substring('release/'.length()) + "." + build_number
      currentBuild.displayName = version
    } else if (v == 'develop') {
      version = branch_name_base + "." + build_number + "-SNAPSHOT";
      currentBuild.displayName = version      
    } else {
      // for all other branches the version number is 0 with an appended build number
      // and for the display name use the jenkins default #n and add the branch name
      // #101 - feature/user/foo
      //version = '0.' + build_number
      version = branch_name_base + "." + build_number
      currentBuild.displayName = "#" + build_number + " - " + branch_name_base
    }
    display_name = currentBuild.displayName
    mvn_initial "versions:set -DnewVersion=${version}"
  }
}

return this
