#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. 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

def workDir = new File('.').canonicalFile
def airTool = new AirPluginTool(args[0], args[1])
final def props = airTool.stepProperties

final def directoryOffset = props['directoryOffset']
final def commandPath = props['commandPath']
final def features = props['features']
final def options = props['options']
def command = 'dism'
def logFile = File.createTempFile('dism-log-', '.tmp')

if (directoryOffset && directoryOffset.trim().length() > 0) {
    workDir = new File(workDir, directoryOffset.trim())
}

if (commandPath && commandPath.trim().length() > 0) {
    command = commandPath.trim()
}

println "Executable: $command"
println "DirectoryOffset: $directoryOffset"
println "Features: $features"
println "Options: $options"

if (!features || features.trim().length() == 0) {
    println "No features specified!"
    System.exit 1
}

def commandList = [command]
commandList << '/online'
commandList << '/norestart'
commandList << '/enable-feature'
features.split('[,\n]').each {
    if (it && it.trim().length() > 0) {
        commandList << "/featurename:${it.trim()}".toString()
    }
}

commandList << "/LogPath:${logFile}"

if (options && options.trim().length() > 0) {
    options.split('[,\n]').each {
        if (it && it.trim().length() > 0)
        commandList << it.trim()
    }
}

try {
    def proc = (commandList as String[]).execute()
    proc.waitFor()
    println proc.in.getText()
    println proc.err.getText()
    logFile.eachLine { println it }
    logFile.delete()
    if (proc.exitValue() != 0 && proc.exitValue() != 3010) System.exit proc.exitValue()
}
catch (Exception e) {
    println "${e.message}"
    logFile.eachLine { println it }
    System.exit 1
}
finally {
    logFile.delete()
}

System.exit 0