module Main where


import System.Console.GetOpt
import System.Environment
import System.Exit
import System.Directory (doesFileExist, doesDirectoryExist)
import Data.Maybe ( fromMaybe, isJust )
import Control.Monad (when)

import qualified Igor2.UI.UIStarter as UI


main = getArgs >>= igorOpts >>= startUIWith

data Options = Options
 { optNoBanner    :: Bool
 , optShowVersion :: Bool
 , optShowHelp    :: Bool
 , optBatch       :: FilePath
 } deriving Show

defaultOptions    = Options
 { optNoBanner    = False
 , optShowVersion = False
 , optShowHelp    = False
 , optBatch       = ""
 }

options :: [OptDescr (Options -> Options)]
options =
 [ Option ['v']      ["version"]
     (NoArg (\ opts -> opts { optShowVersion = True }))
     "Show version number and exit"
 , Option ['h', '?'] ["help"]
     (NoArg (\ opts -> opts { optShowHelp = True }))
     "Show Igor commands and exit"
 , Option [] ["no-banner"]
     (NoArg (\ opts -> opts { optNoBanner = True }))
     "Do not output banner on startup"
 , Option ['b']      ["batch"]
     (ReqArg (\ f opts -> opts { optBatch = f }) "FILE")
     "Run in batch mode with batch FILE"
 ]

igorOpts :: [String] -> IO (Options, [String])
igorOpts argv =
   case getOpt Permute options argv of
      (o,n,[]  ) -> return (foldl (flip id) defaultOptions o, n)
      (_,_,errs) -> error (concat errs ++ usage)

usage = usageInfo header options
    where
    header = "Usage: igor [OPTION...] [CMD1 \\; CMD2 \\; ...]"

startUIWith :: (Options, [String]) -> IO()
startUIWith (opts,cmd) = do
    let batch = optBatch opts
    let noBanner = optNoBanner opts
    when (optShowHelp opts) $
        putStrLn ("IgorII " ++ UI.version) >>
        putStrLn usage >> UI.showHelp >>
        exitWith ExitSuccess
    when (optShowVersion opts) $
        putStrLn ("IgorII " ++ UI.version) >> exitWith ExitSuccess
    if (not.null $ batch)
      then do e <- doesFileExist batch
              if e then UI.runBatch noBanner batch
                else print ("No such file: " ++ (show batch)) >>
                     exitWith (ExitFailure 1)
      else if (not.null $ cmd)
              then UI.runCmdLine noBanner cmd
              else UI.runInteractive
