/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 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.CommandHelper;
import com.urbancode.air.plugin_command.PluginRecoveryObject;
import com.urbancode.commons.util.IO;

final def apTool   = new AirPluginTool(args[0], args[1]);
final def props    = apTool.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);

final int MIN_WAIT_LENGTH = 30;

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

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

try {
    recoveryFile.createNewFile();
}
catch (IOException e) {
    log.error("Error creating msg file!", e);
}

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

    final def time             = Integer.parseInt(props['time'].trim());
    final def agentServiceName = props['agentServiceName'].trim();

    def ch = new CommandHelper(new File('.'));
    def args = [];
    args = ['shutdown', '-r'];
    if (time != null && time != "" ) {
        if (agentServiceName && time < MIN_WAIT_LENGTH) {
            println "[Warning] The time until reboot has been increased to ${MIN_WAIT_LENGTH} seconds because the Agent Service ID is set.";
            println "\tThe agent needs a minimum of ${MIN_WAIT_LENGTH} seconds to safely shutdown. If this step hangs, increase the given Time.";
            time = MIN_WAIT_LENGTH;
        }
        args << '-t';
        args << time;
    }

    println "[Action] Rebooting computer after ${time} seconds...";
    ch.runCommand(args.join(' '), args);

    // Work around code for when reboot does not allow agent to shutdown cleanly
    if (agentServiceName) {
        try {
            println "";
            println "--------------------------------";
            println "";
            println "[Action] Shutting down Agent...";
            def shutdownAgent = ['net', 'stop', agentServiceName];
            ch.runCommand(shutdownAgent.join(' '), shutdownAgent);
        }
        catch (Exception e) {
            println "[Error] Unable to safely shutdown the agent.";
            println "[Possible Solution] Please confirm the Agent Service ID '${agentServiceName}' is correct.";

            // Abort the reboot!
            println "";
            println "--------------------------------";
            println "";
            println "[Action] Aborting reboot...";
            def abortShutdown = ['shutdown', '-a'];
            ch.runCommand(abortShutdown.join(' '), abortShutdown);
            println "[Ok] Reboot aborted.";
            throw e;
        }
    }

    Thread.sleep(9999999999);
}
catch (Exception e) {
    e.printStackTrace();
    recoveryFile.delete();
    throw e;
}
