module PowerShell where

import Paths_native
import Data.Monoid
import Control.Monad
import System.Process
import System.Exit
import System.Directory
import System.FilePath

paramsList :: [(String, String)] -> [String]
paramsList = concatMap (\(p, v) -> ["-" <> p, v])

runPS :: String -> String -> IO String
runPS psPath parStr = do
    let cmdString = "powershell -ExecutionPolicy ByPass -File \"" ++ psPath ++ "\" " ++ parStr
        cmd = shell cmdString
    (ec, out, err) <- readCreateProcessWithExitCode cmd ""
    case ec of
        ExitSuccess -> return out
        ExitFailure c -> error $ "Command `" ++ cmdString ++ "` failed with exit code " ++ show c
                              ++ "\nThe error was:\n" ++ err

runPSStream :: String -> String -> IO ()
runPSStream psPath parStr = do
    let cmdString = "powershell -ExecutionPolicy ByPass -File \"" ++ psPath ++ "\" " ++ parStr
    callCommand cmdString

runDataPS :: String -> [(String, String)] -> IO String
runDataPS psFile params = do
    psPath <- getDataFileName psFile
    runPS psPath parStr
    where parStr = unwords $ paramsList params

getEnvVar :: String -> IO (Maybe String)
getEnvVar v = do
    val <- runDataPS "GetEnvironmentVariable.ps1" [("var", v)]
    case val of
        "" -> return Nothing
        x  -> return (Just x)

setupEnvVars :: IO ()
setupEnvVars = void $ runDataPS "Setup.ps1" []

addPath :: IO ()
addPath = void $ runDataPS "AddPath.ps1" []

download :: String -> IO String
download url = runDataPS "Download.ps1" [("url", url)]

cleanTemp :: IO ()
cleanTemp = do
    dataDir <- getAppUserDataDirectory "native-libs"
    void $ runDataPS "CleanTemp.ps1" [("tempDir", dataDir </> "temp")]