module Main where

import System.Console.GetOpt
import System.Environment

main :: IO ()
main = getArgs >>= compilerOpts >>= cmdopt

data Options = Options 
    { optOutput :: Bool
    , optQuote  :: Bool
    , optDebug  :: Int
    }

defaultOptions = Options
    { optOutput = False
    , optQuote  = False
    , optDebug  = 0
    }

options :: [OptDescr (Options -> Options)]
options =
 [ Option ['o'] ["output"]
   (NoArg (\ opts -> opts { optOutput = True }))
   "Output option"
 , Option ['q'] ["quote"]
   (NoArg (\ opts -> opts { optQuote  = True }))
   "Quote option"
 , Option ['d'] ["debug"]
   (ReqArg (\ d opts -> opts { optDebug = read d }) "LEVEL")
   "debug LEVEL"
 ]

compilerOpts :: [String] -> IO (Options, [String])
compilerOpts argv
 = case getOpt Permute options argv of
     (o,n,[])  -> return (foldl (flip id) defaultOptions o, n)
     (_,_,ers) -> ioError (userError (concat ers ++ usageInfo usageHeader options))

usageHeader = "Usage: cmdopt -o [-q] [-d {0|1|2}] STR [STR ...]"

cmdopt :: (Options,[String]) -> IO ()
cmdopt (o,xs@(_:_))
 | optOutput o = putStr $ unlines 
               $ ["[Option Info]"
                 ,"o(output): "++"ON"
                 ,"q(quote) : "++if optQuote o then "ON" else "OFF"
                 ,"d(debug) : "++show (optDebug o)
                 ,"[Parameter Info]"
                 ,show len ++ " parameter"++if len >1 then "s " else " " ++"specified"
                 ] 
               ++ map showParam (zip [1..] xs)
    where len = length xs
cmdopt _       = ioError (userError (usageInfo usageHeader options))

showParam :: (Int,String) -> String
showParam (n,s) = show n ++": "++s
