module HSH.Helpers.Utils where

import HSH
import Text.StringTemplate.Helpers
import Control.Monad.Error
import System.IO.Error

failIf ioP m = do
  p <- ioP
  if p then fail m else return () 


-- Executes an IO action with a modified environment, where the $PATH variable has the given paths prepended
-- Useful, for example, for getting commands to work from the cron command, 
-- where $PATH may vary from the $PATH you have at user login, with unpredictable results
-- withPath :: [FilePath] -> IO a -> IO a
inPath :: FilePath -> ErrorT String IO ()
inPath p = do
  ErrorT $ do
    res <- tryS $ runIO $ render1 [("p",p)] $ "which $p$"
    case res of 
         Left _ -> return . Left $
                     render1 [("p",p)] "$p$ is not in \\$PATH, maybe you need to modify your shell environment"
         Right _ -> return . Right $ ()



tryS :: IO a -> IO (Either String a)
tryS ma = do
  etRes <- try ma
  return $ case etRes of
    Left e -> Left $ show e
    Right r -> Right r