#!/usr/bin/env groovy
import hudson.model.*
import groovy.json.JsonSlurper


def read_if_exists(file) {
    if (fileExists(file)) {
        return readFile(file).trim()
    } else {
        return ""
    }
}

node {
  println "Running git"
  git url: 'git@git.xarth.tv:twitch/ecs-deploy.git', credentialsId: 'git-aws-read-key'
  sh 'git clean -ffdx'
  println "Finished running git"
  def build_name = "Setup jenkins build"
  def build_var = "jenkins"
  def build_creds = ""

  stage("Print some debug information") {
    echo sh(returnStdout: true, script: 'env')
    println currentBuild
    println params
    sh 'pwd'
    sh 'ls -la'
    sh 'git status'
    sh 'git show'
  }

  // TODO: Find a way to create a clean display name
  //currentBuild.setDisplayName("Build " + String.format("%6.6s", commit_to_deploy))
  while (build_var != "done") {
    def run_next_stage = {
      stage(build_name) {
        sh './helpers/full_promote.sh ' + build_var
        build_var = read_if_exists("next_step")
        build_name = read_if_exists("next_desc")
        build_creds = read_if_exists("next_creds")
        next_builds = read_if_exists("next_builds")
        if (next_builds != "") {
          def values = next_builds.split("\n")
          for (builds in values) {
            build job: builds, wait: false
          }
        }
      }
    }
    if (build_creds != "") {
      withCredentials([file(credentialsId: build_creds, variable: 'AWS_CONFIG_FILE')]) {
        run_next_stage()
      }
    } else {
        run_next_stage()
    }
  }
}
