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

module Erbu.Rsync ( backup )
   where

import Control.Exception ( finally )
import Control.Monad.Reader
import System.Directory ( getTemporaryDirectory, removeFile )
import System.Exit ( ExitCode (..) )
import System.IO ( hClose , hPutStr , openTempFile )
import System.IO.Error ( catch )
import System.Process ( runCommand, waitForProcess )
import Text.Printf ( printf )

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


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

   filters <- lookupEString "rsync.filters" config

   tempPath <- if (optNoAction options)
      then return "TEMPPATH"
      else liftIO $ do
         tempDir <- catch getTemporaryDirectory (\_ -> return ".")
         (tp, th) <- openTempFile tempDir "erbu"
         hPutStr th filters
         hClose th
         return tp

   rsyncArgs <- lookupEString "rsync.args"     config
   srcDir    <- lookupEString "rsync.srcDir"   config
   destPath  <- lookupEString "rsync.destPath" config
   output    <- lookupEString "rsync.output"   config

   let command = printf "%s %s --filter '. %s' %s %s %s"
         tool rsyncArgs tempPath srcDir destPath output

   liftIO $ logMsg COMMAND command

   ec <- if (optNoAction options)
      then return ExitSuccess
      else liftIO $ finally
         ( do ec' <- runCommand command >>= waitForProcess
              return ec' )
         ( removeFile tempPath )

   assessExitCode tool ec

   liftIO $ logMsg STATUS "Backup complete"

