-- Copyright: 2009 Dino Morelli
-- License: BSD3 (see LICENSE)
-- Author: Dino Morelli <dino@ui3.info>

import Control.Monad.Error
import System.Environment ( getArgs )
import System.Exit ( ExitCode (..), exitWith )
import System.IO ( BufferMode ( NoBuffering )
                 , hSetBuffering, stdout, stderr )
import System.Process ( runCommand, waitForProcess )

import Cargs.Common ( Options (..) )
import Cargs.Log ( logMsg, initLogging )
import Cargs.Opts ( parseOpts )


main :: IO ()
main = do
   -- No buffering, it messes with the order of output
   mapM_ (flip hSetBuffering NoBuffering) [ stdout, stderr ]

   initLogging

   -- Parse the args and config file
   optResult <- runErrorT $ (liftIO getArgs) >>= parseOpts

   (options, command) <- either
      ( \err -> do
         putStrLn err
         exitWith $ ExitFailure 255
      )
      return optResult

   -- Got past parsing, now execute the command
   when (optNoAction options) $
      logMsg "No-action mode specified"

   logMsg command

   ec <- case (optNoAction options) of
      True  -> return ExitSuccess
      False -> runCommand command >>= waitForProcess

   logMsg "Done"

   exitWith ec