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

def pipelineJSON = ""
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"

  stage("Getting pipeline as JSON") {
    echo sh(returnStdout: true, script: 'env')
    pipelineJSON = sh(returnStdout: true, script: './helpers/read_pipeline.sh')
    println "Current pipeline JSON"
    println pipelineJSON
    println currentBuild
    println params
    sh 'pwd'
    sh 'ls -la'
    sh 'git status'
    sh 'git show'
  }
}

@NonCPS
def pipelineObjectsDef(pipelineJSON) {
  def pipelineObjects = new groovy.json.JsonSlurper().parseText(pipelineJSON)["steps"]
  def ret = []
  for (pipelineObject in pipelineObjects) {
    def i = [
      "auto": [],
      "manual": [],
    ]
    println pipelineObject
    println pipelineObject["auto"]
    for (auto in pipelineObject["auto"]) {
      def toAppend = auto.toString()
      i["auto"] << toAppend
    }
    for (manual in pipelineObject["manual"]) {
      def toAppend = manual.toString()
      i["manual"]<< toAppend
    }
    ret << i
  }
  return ret
}

def pipelineObjects = pipelineObjectsDef(pipelineJSON)

for (pipelineObject in pipelineObjects) {
  for (auto in pipelineObject["auto"]) {
    stage("Auto promotion of " + auto) {
      def jobName = params.TEAM + "-" + params.SERVICE + "-" + auto
      build job: jobName, wait: true, parameters: [
        string(name: "GIT_COMMIT", value: params.GIT_COMMIT),
        booleanParam(name: "SKIP_DOWNSTREAM", value: true),
      ]
    }
  }
  for (manual in pipelineObject["manual"]) {
    stage("Manual promotion of " + manual) {
      milestone()
      input message: "Proceed?"
      def jobName = params.TEAM + "-" + params.SERVICE + "-" + manual
      build job: jobName, wait: true, parameters: [
        string(name: "GIT_COMMIT", value: params.GIT_COMMIT),
        booleanParam(name: "SKIP_DOWNSTREAM", value: true),
      ]
    }
  }
}