{-# LANGUAGE LambdaCase                 #-}
{-# LANGUAGE MultiWayIf                 #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE TupleSections              #-}

module HS.Cmd.Run where

import qualified Data.Map             as Map
import           Data.Maybe
import qualified Data.Text            as T
import           HS.Install
import           HS.Types
import           System.Process.Typed


-- | command driver to run the given tool
cmdRun :: Cfg -> Maybe InstallMode -> Tool -> ToolArgs -> IO ()
cmdRun :: Cfg -> Maybe InstallMode -> Tool -> ToolArgs -> IO ()
cmdRun Cfg
cfg Maybe InstallMode
mb_im Tool
tl ToolArgs
tas = case Maybe Installation
mb_iln of
    Maybe Installation
Nothing  -> Cfg -> InstallMode -> Compiler -> IO Installation
install Cfg
cfg InstallMode
im Compiler
cp IO Installation -> (Installation -> IO ()) -> IO ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Installation -> IO ()
go
    Just Installation
iln -> Installation -> IO ()
go Installation
iln
  where
    go :: Installation -> IO ()
    go :: Installation -> IO ()
go Installation
iln = ProcessConfig () () () -> IO ()
forall (m :: * -> *) stdin stdout stderr.
MonadIO m =>
ProcessConfig stdin stdout stderr -> m ()
runProcess_ (ProcessConfig () () () -> IO ())
-> ProcessConfig () () () -> IO ()
forall a b. (a -> b) -> a -> b
$ FilePath -> [FilePath] -> ProcessConfig () () ()
proc (Installation -> ToolName -> FilePath
_iln_tool_executable Installation
iln ToolName
tn) [FilePath]
as

    (ToolName
tn,Compiler
cp) = Tool -> (ToolName, Compiler)
toolToCompiler' Tool
tl
    im :: InstallMode
im      = InstallMode -> Maybe InstallMode -> InstallMode
forall a. a -> Maybe a -> a
fromMaybe InstallMode
_cfg_mode Maybe InstallMode
mb_im
    mb_iln :: Maybe Installation
mb_iln  = Compiler -> Map Compiler Installation -> Maybe Installation
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Compiler
cp Map Compiler Installation
_cfg_installations
    as :: [FilePath]
as      = (Text -> FilePath) -> [Text] -> [FilePath]
forall a b. (a -> b) -> [a] -> [b]
map Text -> FilePath
T.unpack ([Text] -> [FilePath]) -> [Text] -> [FilePath]
forall a b. (a -> b) -> a -> b
$ ToolArgs -> [Text]
getToolArgs ToolArgs
tas

    Cfg{Map Compiler Installation
CompilerVersion
InstallMode
Managers
_cfg_installations :: Cfg -> Map Compiler Installation
_cfg_compiler :: Cfg -> CompilerVersion
_cfg_mode :: Cfg -> InstallMode
_cfg_managers :: Cfg -> Managers
_cfg_compiler :: CompilerVersion
_cfg_managers :: Managers
_cfg_installations :: Map Compiler Installation
_cfg_mode :: InstallMode
..} = Cfg
cfg