import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException

properties([parameters([choice(choices: ['vagrant', 'azure'], defaultValue: 'vagrant', description: 'Which Kitchen driver?', name: 'driver')])])

stage('root') {
  try {
    parallel lin1: {
      stage('lin1') {
        node('nomaster') {
          sleep 1
          executeKitchenTarget('lin1', '42sp5p500hf01-lin-rhel-75')
        }
      }
    },
    lin2: {
      stage('lin2') {
        node('nomaster') {
          sleep 60
          executeKitchenTarget('lin2', '42sp6p200-lin-rhel-75')
        }
      }
    },
    win1: {
      stage('win1') {
        node('nomaster') {
          sleep 120
          executeKitchenTarget('win1', '42sp5p500hf01-win-windows-2012r2')
        }
      }
    },
    win2: {
      stage('win2') {
        node('nomaster') {
          sleep 180
          executeKitchenTarget('win2', '42sp6p200-win-windows-2012r2')
        }
      }
    }
  } catch (e) {
    currentBuild.result = 'FAILURE'
    notifyFailed()
    throw e
  } finally {
    println 'currentBuild.result: ' + currentBuild.result
    if (currentBuild.result != 'FAILURE') {
      notifySuccessful()
    }
  }
}

def executeKitchenTarget(String label, String target) {
  checkout([$class: 'GitSCM', branches: [[name: env.BRANCH_NAME]], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[url: 'https://github.com/jpmat296/chef-bo-bip']]])
  stage('rake') {
    sh """#!/bin/bash
      set -x
      chef exec rake
    """
  }
  stage(target) {
    timestamps {
      try {
        sh """#!/bin/bash
          set -x
          bash ~/bin/vms_destroy.sh
          rm -rf .kitchen
          rm -f env.sh && wget -q \$BIP_BASE/env.sh && source \$PWD/env.sh ${params.driver}
          kitchen destroy $target
          kitchen converge $target || kitchen converge $target
          kitchen verify $target
          kitchen destroy $target
        """
      } catch (FlowInterruptedException ie) {
        sh """#!/bin/bash
          set -x
          kitchen destroy $target
        """
      } finally {
        sh """#!/bin/bash
          set -x
          cd .kitchen
          zip -r ../kitchen-$label-logs.zip logs
        """
        archiveArtifacts "kitchen-$label-logs.zip"
      }
    }
  }
}

def notifySuccessful() {
  emailext (
      subject: "SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",

body: """<p>SUCCESSFUL: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
        <p>Check console output at "<a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>""",
      to: 'jp@matsusoft.com'
  )
}

def notifyFailed() {
  emailext (
      subject: "FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'",
      body: """<p>FAILED: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]':</p>
        <p>Check console output at "<a href="${env.BUILD_URL}">${env.JOB_NAME} [${env.BUILD_NUMBER}]</a>"</p>""",
      to: 'jp@matsusoft.com'
  )
}
