import com.urbancode.air.CommandHelper
import com.urbancode.air.AirPluginTool

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()

def regKey = props['regKey'];
def regValue = props['regValue']
def failNotFound = props['failNotFound'].toBoolean()
def ch = new CommandHelper(new File('.'));
def args = [];

try {
    args = ['REG', '/?'];
    ch.runCommand(args.join(' '), args);
    println "Verified REG command executable"
}
catch (e) {
    //Problem running reg.exe
    println e
    System.exit 1
}

try {
    if (regValue) {
        args = ['REG', 'QUERY', regKey, "/v", regValue];
    }
    else {
        args = ['REG', 'QUERY', regKey]
    }
    ch.runCommand(args.join(' '), args);
}
catch (e) {
    //The key was not found

    if (failNotFound) {
        println e
        println "Key not found. Failing the process"
        System.exit 1
    } else {
        println e
        println "Ignoring error, still success if key is already gone"
        System.exit 0
    }
}

try 
{
    if (regValue) {
        args = ['REG', 'DELETE', regKey, '/v', regValue, '/f']
    }
    else {
        args = ['REG', 'DELETE', regKey, '/f'];
    }

    ch.runCommand(args.join(' '), args);
}
catch (e) {
    //Know the key exists but delete failed
    println e
    System.exit 1
}
