module Git.Signature
    ( CSignature
    , Signature(Signature)
    , withSignature
    ) where

import Control.Monad.Catch (bracket)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Foreign (Ptr, alloca, peek)
import Foreign.C (CInt(CInt), CString, withCString)
import Git.Giterr (checkResult)

data Signature = Signature
    { name :: String
    , email :: String
    }

withSignature :: MonadIO m => Signature -> (Ptr CSignature -> IO a) -> m a
withSignature (Signature name email) = liftIO . bracket (signatureNow name email) signatureFree

data CSignature

signatureNow :: String -> String -> IO (Ptr CSignature)
signatureNow name email =
    alloca $ \signaturePtr ->
        withCString name $ \namePtr ->
            withCString email $ \emailPtr -> do
                c_git_signature_now signaturePtr namePtr emailPtr >>= checkResult
                peek signaturePtr

foreign import ccall unsafe "git_signature_now"
    c_git_signature_now :: Ptr (Ptr CSignature)
                        -> CString
                        -> CString
                        -> IO CInt

signatureFree :: Ptr CSignature -> IO ()
signatureFree = c_git_signature_free

foreign import ccall unsafe "git_signature_free"
    c_git_signature_free :: Ptr CSignature -> IO ()

