/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.exec;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteWatchdog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class PowerShell {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(PowerShell.class);
    private final File script;
    private final long timeoutMs = 60 * 1000;

    public PowerShell() throws IOException {
        script = File.createTempFile(getClass().getCanonicalName(), ".ps1");
    }

    public static void main(final String... args) throws IOException {
        final PowerShell ps = new PowerShell();
        ps.thing();
    }

    public void thing() throws IOException {
        logger.info("Created script file: {}", script);
        script.createNewFile();

        final FileOutputStream fos = new FileOutputStream(script);

        fos.write("$pwd = ConvertTo-SecureString '' -asPlaintext -force\r\n".getBytes());
        fos.write("$cred = New-Object System.Management.Automation.PSCredential(\"PSTGC\\aleigh\",$pwd)\r\n".getBytes());
        fos.write("$ses = New-PSSession -ComputerName sef-db1.pstgc.com -Credential $cred\r\n".getBytes());
        fos.write("Invoke-Command -credential $cred -computerName sef-db1.pstgc.com -scriptBlock {$tmpfile = [IO.Path]::GetTempFileName();(get-WmiObject win32_logicaldisk | ConvertTo-Xml).save($tmpfile);Get-Content $tmpfile;Remove-Item $tmpfile}\r\n".getBytes());
        fos.write("Remove-PSSession $ses\r\n".getBytes());

        fos.close();

        final String line = "PowerShell -F " + script.getAbsolutePath();
        final CommandLine cmdLine = CommandLine.parse(line);
        final DefaultExecutor executor = new DefaultExecutor();

        final ExecuteWatchdog watchdog = new ExecuteWatchdog(timeoutMs);
        executor.setWatchdog(watchdog);

        final int exitValue = executor.execute(cmdLine);

        logger.info("Return value {}", Integer.valueOf(exitValue));
    }
}
