pipeline {
  agent any

  parameters {
    booleanParam(name: 'NIGHTLY_BUILD',
                 defaultValue: false,
                 description: "DO NOT SELECT")
  }

  stages {
    stage('Pre-Build') {
      steps {
        sh """
        echo "now installing nodeJs ..."
        echo "env.TAG_NAME:"
        echo "${env.TAG_NAME}"
        bash ./tools/deploy/preBuild.sh
        """
      }
    }
    stage('Build') { //Execute build commands
      steps {
        sh """
        echo "need to run npm test in the future"
        npm run test
        """
           // npm test
           //need to add this back in
           // npm run lint
         }
       }
    stage('Post-Build') { //bundle the build and install deploy dependencies(GCS SDK)
      when {
        expression { return ("${env.TAG_NAME}" != "null" || "${params.NIGHTLY_BUILD}" == "true") }
      }
      steps {
        sh '''
        echo "Bundle the build and install deploy dependencies"
        bash ./tools/deploy/postBuild.sh
        '''
      }
    }
    stage('Test-Deploy') {
      when {
         expression { return ("${env.TAG_NAME}" != "null" || "${params.NIGHTLY_BUILD}" == "true") }
      }
      steps {
        sh '''
			bash tools/deploy/gcs/deploy_to_aws.sh
        '''
      }
    }
    stage('Bat-Test') {
       when {
         expression { return ("${env.TAG_NAME}" != "null" || "${params.NIGHTLY_BUILD}" == "true") }
       }
       steps {
         sh  '''
             echo "Run FE BAT tests"
             bash tools/deploy/bat-test.sh
             '''
         script {
           allure includeProperties: false, jdk: '', results: [[path: 'allure-results']]
           sh '''
# Uncomment once FE tests work with no errors!
#               if [ `grep -r '\"status\": \"failed\"' ./allure-results | wc -l` -ne 0 ] || \
#                  [ `grep -r '\"status\": \"broken\"' ./allure-results | wc -l` -ne 0 ] ; then
#                   rm EC2_ID
#                   exit 1
#               else
                   aws ec2 terminate-instances --instance-ids `cat EC2_ID`
#               fi
           '''
         }
       }
    }
    stage('Release-cloud') { //deploy build(uploading to GCS currently)
      when {
         expression { return ("${env.TAG_NAME}" != "null" || "${params.NIGHTLY_BUILD}" == "true") }
      }
      steps {
        sh """
        echo "Deploy build to cloud"
        bash tools/deploy/upgrade.sh
        """
      }
    }
  	stage('Release-github') { //deploy build(uploading to GCS currently)
      when {
         expression { return ("${env.TAG_NAME}" != "null" || "${params.NIGHTLY_BUILD}" == "true") }
      }
      steps {
        sh """
        echo "Deploy build to github"
        bash tools/deploy/release_to_git.sh ${env.TAG_NAME}
        """
      }
    }
  }
  environment { //Pipeline global environment
    BUILD_AGENT = "Jenkins"
    JENKINS_GIT_BRANCH = "${env.GIT_BRANCH}"
    JENKINS_GIT_COMMIT = "${env.GIT_COMMIT}"
    JENKINS_BUILD_NUMBER = "${env.BUILD_NUMBER}"
    JENKINS_GIT_TAG = get_git_tag(env.TAG_NAME)
    DEPLOY_TAR = "bundle.tgz"
    DEPLOY_TAR_WITH_TAG = "ice_console_${env.TAG_NAME}.tgz"
    JENKINS_BLUE_URL = get_blue_url()
    JENKINS_ALLURE_URL = get_allure_url()
    FRONTEND_INSTANCE_NAME = "fe-staging-5"
    VPS_PEM = credentials('VPS_PEM')
    LAUNCH_TEMPLATE = "lt-08041e1e2093aea50"
    FE_BUCKET="s3://ice-console/ice-console2"
  }

  post { //End-of-Pipeline tasks.
    cleanup {
      deleteDir()
    }
    unsuccessful {
      sh '''
        if [[ -f "EC2_ID" ]]; then
            aws ec2 terminate-instances --instance-ids `cat EC2_ID`
        fi
# Uncomment once FE tests work with no errors!
#        if [[ `aws s3 ls ${FE_BUCKET}/${DEPLOY_TAR_WITH_TAG} | wc -l` -gt 0 ]]; then
#            aws s3 rm ${FE_BUCKET}/${DEPLOY_TAR_WITH_TAG}
#        fi
      '''
    }
    failure {
      emailext attachLog: true, body: """Jenkins job has failed:
      Repo: ice-console (${env.GIT_URL})
      Branch: ${env.BRANCH_NAME}
      Git commit id: ${env.GIT_COMMIT}
      The commit was made by: ${env.GIT_COMMITTER_NAME}

      Jenkins build number: ${env.BUILD_NUMBER}
      View jenkins run details: ${env.JENKINS_BLUE_URL}
      """, compressLog: true, subject: 'JENKINS: Ice-Console Build Failed', to: 'jenkins@virtualpowersystems.com'
      slackSend (color: '#FF0000', channel: "#builds", message: "FAILED: Building '${env.JOB_NAME} [${env.BUILD_NUMBER}]'. See '${env.JENKINS_BLUE_URL}' for details.\nAllure Report: '${env.JENKINS_ALLURE_URL}'")
      slackSend (color: '#FF0000', channel: "#frontend", message: "FAILED: Building '${env.JOB_NAME} [${env.BUILD_NUMBER}]'. See '${env.JENKINS_BLUE_URL}' for details.")

    }
    success {
      script {
        if ("${env.TAG_NAME}" != "null") {
          emailext attachLog: true, body: """New Ice-Console Build released:
          Release Page: https://github.com/vpsinc/ice-console/releases/tag/${env.TAG_NAME}
          Repo: ice-console (${env.GIT_URL})
          Branch: ${env.BRANCH_NAME}
          Git commit id: ${env.GIT_COMMIT}
          The commit was made by: ${env.GIT_COMMITTER_NAME}

          Jenkins build number: ${env.BUILD_NUMBER}
          View jenkins run details: ${env.JENKINS_BLUE_URL}
          """, compressLog: true, subject: "New Ice-Console Build released: ${env.TAG_NAME}", to: 'qa@virtualpowersystems.com'
          slackSend (color: '#008000', channel: "#qa-releases", message: "SUCCESSS: Building '${env.JOB_NAME} [${env.BUILD_NUMBER}]'. See '${env.JENKINS_BLUE_URL}' for details.\nAllure Report: '${env.JENKINS_ALLURE_URL}'")
        }
      }
      emailext attachLog: true, body: """Jenkins job has succeeded:
      Repo: ice-console (${env.GIT_URL})
      Branch: ${env.BRANCH_NAME}
      Git commit id: ${env.GIT_COMMIT}
      The commit was made by: ${env.GIT_COMMITTER_NAME}

      Jenkins build number: ${env.BUILD_NUMBER}
      View jenkins run details: ${env.JENKINS_BLUE_URL}
      """, compressLog: true, subject: 'JENKINS: Ice-Console Build Succeeded', to: 'jenkins@virtualpowersystems.com'
      slackSend (color: '#008000', channel: "#frontend", message: "SUCCESSS: Building '${env.JOB_NAME} [${env.BUILD_NUMBER}]' See '${env.JENKINS_BLUE_URL}' for details.")
      slackSend (color: '#008000', channel: "#builds", message: "SUCCESSS: Building '${env.JOB_NAME} [${env.BUILD_NUMBER}]' See '${env.JENKINS_BLUE_URL}' for details.\nAllure Report: '${env.JENKINS_ALLURE_URL}'")
    }
  }
}

def get_git_tag(tag_name) {
  return (tag_name == null)? "":"${tag_name}"
}

def get_blue_url() {
  print("${env.BUILD_URL}")
  def tokens = "${env.BUILD_URL}".tokenize("/")
  for (i = 0; i < tokens.size(); i++) {
    print(tokens[i])
  }
  def protocol = tokens[0]
  def ip_port = tokens[1]
  def job_name = tokens[3]
  def branch = tokens[5]
  def build_number = tokens[6]

  return protocol + "//" + ip_port + "/blue/organizations/jenkins/" + job_name + "/detail/" + branch + "/" + build_number + "/pipeline/"
}

def get_allure_url() {
  print("${env.BUILD_URL}")
  def tokens = "${env.BUILD_URL}".tokenize("/")
  for (i = 0; i < tokens.size(); i++) {
    print(tokens[i])
  }
  def protocol = tokens[0]
  def ip_port = tokens[1]
  def job_name = tokens[3]
  def branch = tokens[5]
  def build_number = tokens[6]

  return protocol + "//" + ip_port + "/job/" + job_name + "/job/" + branch + "/" + build_number + "/allure/"
}
