/*
* 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 java.io.File

import com.urbancode.air.XTrustProvider
import com.urbancode.air.plugin.docker.DockerUtils
import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper
import com.urbancode.ud.client.ResourceClient
import com.urbancode.ud.client.ComponentClient
import com.urbancode.ud.client.ApplicationClient
import com.urbancode.ud.client.EnvironmentClient

XTrustProvider.install()

// Get step properties
def airTool = new AirPluginTool(this.args[0], this.args[1])
def props = airTool.getStepProperties()
def workdir = new File('.')
String composeFilesRaw           = props['composeFiles']
String composeProjectName        = props['composeProjectName']
String composeOptions            = props['composeOptions']
String timeout                   = props['timeout']
String scaleArguments            = props['scaleArguments']
String envPropValues             = props['envPropValues']
String scriptPathsRaw            = props['scriptPaths']
String commandPath               = props['commandPath']?:"docker-compose"
Boolean saveScript               = Boolean.valueOf(props['saveScript'])

// Sanitize properties
List<String> scriptPaths = DockerUtils.toTrimmedList(scriptPathsRaw, ',')
List<String> composeFilePaths = DockerUtils.toTrimmedList(composeFilesRaw, '\n')
if (!composeFilePaths) {
    composeFilePaths << 'docker-compose.yml'
}

CommandHelper ch = new CommandHelper(workdir)


// compose up arguments
List<String> composeScaleArgs = [DockerUtils.findDockerComposeExecutable(commandPath)]
if (composeOptions) {
    composeScaleArgs << composeOptions
}
if (composeProjectName) {
    composeScaleArgs << '-p'
    composeScaleArgs << composeProjectName
}
composeFilePaths.each { path ->
    composeScaleArgs << '-f'
    composeScaleArgs << path
}
composeScaleArgs << 'scale'

// Timeout Option
if (timeout) {
    composeScaleArgs << '--timeout'
    composeScaleArgs << timeout
}

// Scale properties
List tempScaleVals = DockerUtils.toTrimmedList(scaleArguments,'\n|,')
Map<String, String> scalePairs = DockerUtils.toKeyValueMap(tempScaleVals, "=")
scalePairs.each { pair ->
    composeScaleArgs << "${pair.getKey()}=${pair.getValue()}"
}

// Environment properties
Map<String, String> envVars = [:]
if(envPropValues) {
    List tempEnvVals = DockerUtils.toTrimmedList(envPropValues,'\n|,')
    envVars = DockerUtils.toKeyValueMap(tempEnvVals, "=")
}

// command helper arguments
List<String> args = []
File script
final Boolean isWindows = System.getProperty('os.name').contains('Windows')
if (isWindows) {
    script = File.createTempFile("script", ".bat", workdir)

    // Write the Environment Variables
    envVars.each { var ->
        script << "set ${var.getKey()}=${var.getValue()}\n"
    }

    args << 'cmd'
    args << '/C'
}
else {
    script = File.createTempFile("script", ".sh", workdir)

    // Environment files
    scriptPaths.each { filePath ->
        def envScript = new File(filePath)
        if (envScript.exists()) {
            envScript.setExecutable(true)
            script << "source \"${filePath}\"\n"
        }
        else {
            throw new RuntimeException("Could not find env file at ${filePath}")
        }
    }

    // Write the Environment Variables
    envVars.each { var ->
        script << "export ${var.getKey()}=\"${var.getValue()}\"\n"
    }
}
if (!saveScript) {
    script.deleteOnExit()
}
script.setExecutable(true)
script << composeScaleArgs.join(' ')

args << script.getCanonicalPath()

// Print Script Contents
println "============ Script Contents ============"
println script.getText()
println "========================================="

// Run Compose
ch.runCommand("Executing Compose Scale...", args)
