-- (partly) from http://cgi.cse.unsw.edu.au/~dons/blog/2007/03
module Process where

import System.Process
import Control.Exception
import System.IO
import System.Exit
import Text.Regex
import Char

--
-- Run a normal shell command
--
--
run s = handle (fail . show) $ do
    (ih,oh,eh,pid) <- runInteractiveCommand s
    so <- hGetContents oh
    se <- hGetContents eh
    hClose ih
    ex <- waitForProcess pid
    case ex of
        ExitFailure e      -> fail $ "Command " ++ show s ++ " failed with status: " ++ show e ++ ", stderr: " ++ se ++ ", stdout: " ++ so
        _  | otherwise     -> return so

run_with_stdin cmd stdin = handle (fail . show) $ do
    (ih, oh, eh, pid) <- runInteractiveCommand cmd
    hPutStr ih stdin
    so <- hGetContents oh
    se <- hGetContents eh
    hClose ih
    ex <- waitForProcess pid
    case ex of
        ExitFailure e   -> fail $ "Command " ++ show cmd ++ " failed with status: " ++ show e ++ ", stderr: " ++ se ++ ", stdout: " ++ so
        _ | otherwise   -> return so

quoteMeta :: String -> String
-- quoteMeta = concatMap (\c -> if (isAlphaNum c || c == ' ') then [c] else ['\\', c])
quoteMeta = concatMap (\c -> if (isOk c) then [c] else ['\\', c])

isOk :: Char -> Bool
isOk c =
    (isAlphaNum c) || (isOkToo c)

isOkToo c | c == ' ' = True
          | c == '-' = True
          | c == '/' = True
          | c == '=' = True
          | c == '.' = True
          | otherwise = False
