/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.openshift.OpenShiftHelper

// Get step properties
def apTool   = new AirPluginTool(args[0], args[1])
def inProps  = apTool.getStepProperties()

String url          = inProps['url'].trim()
String username     = inProps['username']
String password     = inProps['password']
String token        = inProps['token']
String insecure     = inProps['insecure']
String home         = inProps['home']?.trim()
String project      = inProps['project'].trim()
String template     = inProps['template'].trim()
String parameter    = inProps['parameter']?.trim()

// Set up helper
File workDir = new File(".").canonicalFile
OpenShiftHelper osh = new OpenShiftHelper(workDir, home)
osh.login(url, username, password, token, insecure.toBoolean())
osh.setProject(project)

def temp = File.createTempFile('temp', '.txt', workDir)
temp.deleteOnExit()

def args = []
def params = []

// Get available parameters from template, if parameter file is given
if (parameter) {
    args << 'process'
    args << '-f'
    args << template
    args << '--parameters'
    osh.runCommand("[Action] Looking for parameters to replace...", args) { Process proc ->
        def (String sout, String serr) = osh.captureCommand(proc)
        if (serr) {
            println ('[Error] Parameter search failed.')
            println (serr)
            println (sout)
            System.exit(1)

        }
        else {
            println ('[Ok] Available parameters found.')
            def lines = sout.split('\n')
            lines.each { line ->
                params << (line.split(" "))[0]
            }
        }
    }
}

// Process template into resource list
args = []
args << 'process'
args << '-f'
args << template
// Add parameter name=value if present in both the parameters file and the template
if (parameter) {
    def fileContents = new File(parameter).text.split('\n')
    fileContents.each { line ->
        params.each { param ->
            if (line.substring(0, line.indexOf("=")) == param) {
                println line
                args << line
            }
        }


    }
}
osh.runCommand("[Action] Executing Process Operation...", args) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    if (serr) {
        println ('[Error] Process operation failed.')
        println (serr)
        println (sout)
        System.exit(1)

    }
    else {
        println ('[Ok] Process operation succeeded.')
        println (sout)
        temp << sout
    }
}

// Create objects from resource list
def applyArgs = []
applyArgs << 'apply'
applyArgs << '-f'
applyArgs << temp.getAbsolutePath()
osh.runCommand("[Action] Executing Apply Operation...", applyArgs) { Process proc ->
    def (String sout, String serr) = osh.captureCommand(proc)
    if (serr) {
        println ('[Error] Apply operation failed.')
        println (serr)
        println (sout)
        System.exit(1)
    }
    else {
        println ('[Ok] Apply operation succeeded.')
        println (sout)
    }
}