/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2002-2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
package com.urbancode.air.plugin.iisconfiguration.helper
import com.urbancode.shell.Shell;

class PowerShellHelper {
    final File PLUGIN_HOME = new File(System.getenv().get("PLUGIN_HOME"))
    public PowerShellHelper(){
        def arch = getArch()
        def libraryPath = new File(PLUGIN_HOME, "lib/native/${arch}/WinAPI.dll")
        System.setProperty("com.urbancode.winapi.WinAPI.dllPath", libraryPath.absolutePath)
    }

    public runPSFile(File psFile){
        def cmdArgs = []
        cmdArgs << "powershell.exe" << "-NonInteractive" << "-ExecutionPolicy" << "unrestricted" << "-NoLogo" << "-NoProfile" << "-File" << "\"${psFile.getCanonicalPath()}\""
        println("Running PowerShell command: ${cmdArgs.join(" ")}")
        def shell = new Shell(cmdArgs as String[])
        shell.execute()
        def proc = shell.process
        def oStream = new ByteArrayOutputStream()
        def eStream = new ByteArrayOutputStream()
        proc.waitForProcessOutput(oStream, eStream)
        def outputString = oStream.toString()
        println("Completed PowerShell command ${outputString}${eStream.toString()}")
    }

    String getArch() {
        String result
        String arch = System.getProperty("os.arch").toLowerCase(Locale.US)

        if (arch.indexOf("amd64") > -1 || arch.indexOf("x64") > -1 || arch.indexOf("x86_64") > -1) {
            result = "x64"
        }
        else if (arch.indexOf("x86") > -1 || arch.indexOf("386") > -1 || arch.indexOf("486") > -1 ||
                 arch.indexOf("586") > -1 || arch.indexOf("686") > -1 || arch.indexOf("pentium") > -1) {
            result = "x86"
        }
        else {
            result = "unknown"
        }

        return result
    }
}
