/*
* 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.plugin_command.PluginRecoveryObject;
import com.urbancode.air.AirPluginTool;
import com.urbancode.air.CommandHelper;
import com.urbancode.air.ExitCodeException;
import com.urbancode.air.plugin.linux.RebootHelper;
import com.urbancode.commons.util.IO;

final def airTool = new AirPluginTool(args[0], args[1])
final def props = airTool.getStepProperties()

final def AGENT_HOME = System.getenv("AGENT_HOME");
final def dialogueId = System.getenv("UD_DIALOGUE_ID");

File agentHome= new File(AGENT_HOME);
File recoveryDir = new File(agentHome, "var/recovery");
File recoveryFile = File.createTempFile("recovery", ".rec", recoveryDir);
Properties outProps = new Properties();

outProps.put("Status", "Success");
outProps.put("exitCode", "0");

PluginRecoveryObject pro = new PluginRecoveryObject(
    dialogueId,
    201,
    "exec_response",
    outProps);

try {
    IO.createNewFile(recoveryFile);
}
catch (IOException e) {
    println "Error creating msg file!"
}

try {
    try {
        ObjectOutputStream outStream = new ObjectOutputStream(IO.openOutput(recoveryFile));
        try {
            outStream.writeObject(pro);
        }
        finally {
            outStream.close();
        }
    }
    catch (Exception e) {
        throw e;
    }

    final def time = props['time'];
    new RebootHelper(time).run();
    Thread.sleep(9999999999);
}
catch (Exception e) {
    recoveryFile.delete();
    throw e;
}
