/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Build
 * IBM UrbanCode Deploy
 * IBM UrbanCode Release
 * IBM AnthillPro
 * (c) Copyright IBM Corporation 2016. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */
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
    }
}
