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

import Control.Monad.Error
import Control.Monad.Reader
import Data.Map hiding ( map )
import Data.Maybe ( isJust )
import Prelude hiding ( lookup )
import System.Environment ( getArgs )
import System.Exit ( ExitCode (..), exitWith )

import Erbu.Common ( Env (..), runErbu, turnOffBuffering
   , exitFailWithMsg, reportFailureLog )
import Erbu.Encfs ( mount, umount )
import Erbu.ErmntOpts ( Options (..), parseOpts )


main :: IO ()
main = do
   -- No buffering, it messes with the order of output
   turnOffBuffering


   -- Command-line processing
   -- optResult is an (Either String (ConfMap, Options))
   optResult <- runErrorT $ (liftIO getArgs) >>= parseOpts


   -- Assess result of cli parse, exit if necessary with messages
   (options, config) <- either exitFailWithMsg return optResult


   -- Perform the mount operation
   mountResult <- runErbu (Env options config) $ do
      let doingEnc = isJust $ lookup "encfs.passphrase" config
      unless doingEnc $ throwError $
         "Config file does not contain encfs parameters" 

      if (not $ optUmount options)
         then mount
         else umount

      return ExitSuccess


   -- Assess the result
   exitWith =<< either reportFailureLog return mountResult

