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

module Erbu.Encfs ( mount, umount )
   where

import Control.Monad.Reader
import System.Exit ( ExitCode (..) )
import System.IO ( hClose, hPutStr)
import System.Process 
   ( runCommand
   , runInteractiveCommand
   , waitForProcess )
import Text.Printf ( printf )

import Erbu.Common ( Env (..), Erbu, assessExitCode )
import Erbu.ErmntOpts ( Options (..) )
import Erbu.Log ( LogEvent (..), logMsg )
import Fez.Control.Monad.Error ( lookupEString )


mount :: Erbu ()
mount = do
   config <- asks envConfig
   options <- asks envOptions
   let tool = "encfs"

   encfsRootDir <- lookupEString "encfs.rootDir" config
   encfsMountPoint <- lookupEString "encfs.mountPoint" config
   let command = printf "%s --public -S %s %s"
         tool encfsRootDir encfsMountPoint

   encfsPassphrase <- lookupEString "encfs.passphrase" config

   liftIO $ logMsg COMMAND command

   -- In order to mount encfs unattended, we're calling it with
   -- the -S switch and then writing the passphrase to its stdin
   -- For that we use an interactive process:
   ec <- if (optNoAction options)
      then return ExitSuccess
      else liftIO $ do
         (hIn, _, _, pid) <- runInteractiveCommand command
         hPutStr hIn encfsPassphrase
         hClose hIn
         waitForProcess pid

   assessExitCode tool ec


umount :: Erbu ()
umount = do
   config <- asks envConfig
   options <- asks envOptions
   let tool = "fusermount"

   encfsMountPoint <- lookupEString "encfs.mountPoint" config
   let command = printf "%s -u %s" tool encfsMountPoint

   liftIO $ logMsg COMMAND command

   ec <- if (optNoAction options)
      then return ExitSuccess
      else liftIO $ runCommand command >>= waitForProcess

   assessExitCode tool ec

