/* Jenkinsfile
 * Controls multibranch pipeline builds of the CUI project.
 */

def email_to  = 'dvanhoozer@42six.com'
def err       = null

currentBuild.result = "SUCCESS"

// ############################################################
try {
  node {

    stage 'Checking out code'
    checkout scm
    stage 'Updating Gems'
    sh '''
      #!/bin/bash -l
      . /etc/profile
      cd "${WORKSPACE}"
      rvm use 2.3.3@deap
      bundle install
    '''

    stage 'Migrate Database'
    sh '''
      #!/bin/bash -l
      . /etc/profile
      cd "${WORKSPACE}"
      rvm use 2.3.3@deap
      bundle exec rake db:migrate
    '''

    // TODO: Only do this stage is BRANCH_NAME is a CPP branch
    stage 'CPP Tests'
    sh '''
      #!/bin/bash -l
      . /etc/profile
      cd "${WORKSPACE}"
      rvm use 2.3.3@deap
      bundle exec rake cpp:test
    '''


    publishHTML target: [
      reportName:   'Test Coverage',
      reportDir:    'coverage',
      reportFiles:  'index.html',
      keepAll:                true,
      alwaysLinkToLastBuild:  true,
      allowMissing:           true
    ]

    publishHTML target: [
      reportName:   'RCov Test Coverage',
      reportDir:    'coverage/rcov',
      reportFiles:  'index.html',
      keepAll:                true,
      alwaysLinkToLastBuild:  true,
      allowMissing:           true
    ]


    //
    // for this stage, may only want to build the image if one of master,
    // tester or develop branches
    //
    stage 'Creating docker image'
    //sh('cd "${WORKSPACE}" && ./bin/docker_cui_create.sh')

    //
    // same rules would apply in this stage as the previous stage
    //
    stage 'Starting docker containers'
    // sh('cd "${WORKSPACE}" && ./bin/docker_cui.sh')

    // stage 'Deploying to test machine'

  } // node {
} // try {


// ############################################################
catch(Exception e) {
    err = e
    currentBuild.result = "FAILURE"
}


// ############################################################
finally {
  if (currentBuild.result != "ABORTED" && currentBuild.result != "SUCCESS") {
    node {
      // normal jenkins mailer
      step([
        $class:                   'Mailer',
        notifyEveryUnstableBuild: true,
        recipients:               "${email_to}",
        sendToIndividuals:        true
      ])
    } // node {
  } // if (currentBuild.result !=

  if(err){
    throw err
  }
} // finally {


