{- | Monadic interface to @libzip@.

Most of the operations on zip archive happen within 'Archive' monad
(see 'withArchive').
Partial reading of the files in the archive may be performed from
within 'Entry' monad (see 'fromFile').
Both 'Archive' and 'Entry' are monad transformers over 'IO', and allow
for IO with single and double 'lift'ing respectingly.

Note: LibZip does not handle text encodings. Even if its API accepts
'String's (e.g. in 'sourceBuffer'), character codes above 255 should
not be used.  The user is responsible of proper encoding the text
data.

/Examples/

List files in the zip archive:

@
import System.Environment (getArgs)
import Codec.Archive.LibZip

main = do
  (zipfile:_) <- getArgs
  files <- withArchive [] zipfile $ fileNames []
  mapM_ putStrLn files
@

Create a zip archive and a add file to the archive:

@
import System.Environment (getArgs)
import Codec.Archive.LibZip

main = do
  (zipfile:_) <- getArgs
  withArchive [CreateFlag] zipfile $ do
     zs <- sourceBuffer \"Hello World!\"
     addFile \"hello.txt\" zs
@

Extract and print a file from the zip archive:

@
import System.Environment (getArgs)
import Codec.Archive.LibZip

main = do
  (zipfile:file:_) <- getArgs
  bytes <- withArchive [] zipfile $ fileContents [] file
  putStrLn bytes
@

See also an implementation of a simple zip archiver @hzip.hs@ in the
@examples/@ directory of the source distribution.

-}
module Codec.Archive.LibZip
    (
    -- * Types
      Archive
    , Entry
    , ZipStat(..)
    -- * Archive operations
    , withArchive, getZip
    , numFiles, fileName, nameLocate, fileNames
    , fileSize, fileSizeIx
    , fileStat, fileStatIx
    , deleteFile, deleteFileIx
    , renameFile, renameFileIx
    , addFile, addDirectory
    , replaceFile, replaceFileIx
    , sourceBuffer, sourceFile, sourceZip
    , PureSource(..), sourcePure
    , getComment, setComment, removeComment
    , getFileComment, getFileCommentIx
    , setFileComment, setFileCommentIx
    , removeFileComment, removeFileCommentIx
    , unchangeFile, unchangeFileIx
    , unchangeArchive, unchangeAll
    -- * File reading operations
    , fromFile, fromFileIx
    , readBytes, skipBytes, readContents
    , fileContents, fileContentsIx
    -- * Flags and options
    , OpenFlag(..)
    , FileFlag(..)
    , ZipCompMethod(..)
    , ZipEncryptionMethod(..)
    -- * Exception handling
    , ZipError(..)
    , catchZipError
    -- * Re-exports
    , lift
    ) where

import Bindings.LibZip
import Codec.Archive.LibZip.Types
import Codec.Archive.LibZip.Errors

import Data.Time.Clock (UTCTime, getCurrentTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Data.Word (Word8)
import Control.Monad.State.Strict
    (StateT(..), MonadState(..), MonadTrans(..), lift, liftM)
import Foreign.C.Error (Errno(..), eINVAL)
import Foreign.C.String (withCString, withCStringLen, peekCString)
import Foreign.C.Types (CInt, CSize)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Array (allocaArray, peekArray, withArrayLen, pokeArray)
import Foreign.Marshal.Utils (with)
import Foreign.Ptr (Ptr, nullPtr, castPtr)
import Foreign.Storable (Storable, peek, poke, pokeElemOff, sizeOf)
import qualified Control.Exception as E

--
-- Types
--

-- | Monadic computation with a zip archive. See 'withArchive'.
type Archive a = StateT Zip IO a

-- | Monadic computation to read from open archive entries.
-- See 'fromFile' and 'fromFileIx'.
type Entry a = StateT
    (ZipFile,Int,[FileFlag])   -- (file, position index, access flags)
    (StateT Zip IO)            -- archive monad
    a

--
-- Archive operations
--

-- | Top-level wrapper for operations with an open
-- archive. 'withArchive' opens and closes the file
-- automatically. On error it throws 'ZipError'.
withArchive :: [OpenFlag]  -- ^ Checks for consistency or existence.
            -> FilePath    -- ^ Filename of the zip archive.
            -> Archive a   -- ^ Action to do with the archive.
            -> IO a
withArchive flags path action =
  withCString path $ \path' ->
  alloca $ \errp ->
  c'zip_open path' (combine flags) errp >>= \z ->
  if z == nullPtr
    then peek errp >>= E.throwIO. errFromCInt
    else do
      r <- fst `liftM` runStateT action z
      e <- c'zip_close z
      if e /= 0
        then get_error z >>= E.throwIO
        else return r

-- | Get the number of entries in the archive.
numFiles :: Archive Int
numFiles = do
  z <- getZip
  lift $ fromIntegral `liftM` c'zip_get_num_files z

-- | Get name of an entry in the archive by its index.
fileName :: [FileFlag]  -- ^ 'FileUNCHANGED' flag can be used.
         -> Int         -- ^ Position index of a file in the archive.
         -> Archive FilePath  -- ^ Name of the file in the archive.
fileName flags i = do
  z <- getZip
  lift $ do
    n <- c'zip_get_name z (fromIntegral i) (combine flags)
    doIf' (n /= nullPtr) z $ peekCString n

-- | Locate an entry (get its index) in the archive by its name.
nameLocate :: [FileFlag]  -- ^ Filename lookup mode.
           -> FilePath    -- ^ Name of the file in the archive.
           -> Archive (Maybe Int)  -- ^ 'Just' position index if found.
nameLocate flags name = do
  z <- getZip
  lift $
    withCString name $ \name' -> do
    i <- fromIntegral `liftM` c'zip_name_locate z name' (combine flags)
    if i < 0
       then return Nothing
       else return (Just i)

-- | Get names of all entries (files and directories) in the archive.
fileNames :: [FileFlag]  -- ^ 'FileUNCHANGED' flag is accepted.
          -> Archive [FilePath]
fileNames flags = do
  n <- numFiles
  mapM (fileName flags) [0..n-1]

-- | Get size of a file in the archive.
fileSize :: [FileFlag]  -- ^ Filename lookup mode, 'FileUNCHANGED' can be used.
         -> FilePath    -- ^ Name of the file in the archive.
         -> Archive Int -- ^ File size.
fileSize flags name = fileStat flags name >>= return . zs'size

-- | Get size of a file in the archive (by index).
fileSizeIx :: [FileFlag]  -- ^ 'FileUNCHANGED' is accepted.
           -> Int         -- ^ Position index of a file in the archive.
           -> Archive Int -- ^ File size.
fileSizeIx flags i = fileStatIx flags i >>= return . zs'size

-- | Get information about a file in the archive.
fileStat :: [FileFlag]  -- ^ Filename lookup mode, 'FileUNCHANGED' can be used.
         -> FilePath    -- ^ Name of the file in the archive.
         -> Archive ZipStat  -- ^ Infomation about the file.
fileStat flags name = do
  z <- getZip
  lift $
       withCString name $ \name' ->
       alloca $ \stat -> do
       c'zip_stat_init stat
       r <- c'zip_stat z name' (combine flags) stat
       doIf' (r == 0) z $ toZipStat =<< peek stat

-- | Get information about a file in the archive (by index).
fileStatIx :: [FileFlag]  -- ^ 'FileUNCHANGED' can be used.
           -> Int         -- ^ Position index of a file in the archive.
           -> Archive ZipStat  -- ^ Information about the file.
fileStatIx flags i = do
  z <- getZip
  lift $
       alloca $ \stat -> do
       r <- c'zip_stat_index z (fromIntegral i) (combine flags) stat
       doIf' (r == 0) z $ toZipStat =<< peek stat

-- | Delete file from the archive.
deleteFile :: [FileFlag]  -- ^ Filename lookup mode.
           -> FilePath    -- ^ Filename.
           -> Archive ()
deleteFile flags name = do
  mbi <- nameLocate flags name
  maybe (lift $ E.throwIO ErrNOENT) deleteFileIx mbi

-- | Delete file (referenced by position index) from the archive.
deleteFileIx :: Int  -- ^ Position index of a file in the archive.
             -> Archive ()
deleteFileIx i = do
  z <- getZip
  r <- lift $ c'zip_delete z (fromIntegral i)
  if r == 0
     then return ()
     else lift $ get_error z >>= E.throwIO

-- | Rename file in the archive.
renameFile :: [FileFlag]  -- ^ Filename lookup mode.
           -> FilePath    -- ^ Old name.
           -> FilePath    -- ^ New name.
           -> Archive ()
renameFile flags oldname newname = do
  mbi <- nameLocate flags oldname
  maybe (lift $ E.throwIO ErrNOENT) (\i -> renameFileIx i newname) mbi

-- | Rename file (referenced by position index) in the archive.
renameFileIx :: Int  -- ^ Position index of a file in the archive.
             -> FilePath -- ^ New name.
             -> Archive ()
renameFileIx i newname = do
  z <- getZip
  r <- lift $ withCString newname $ c'zip_rename z (fromIntegral i)
  if r == 0
     then return ()
     else lift $ get_error z >>= E.throwIO

-- | Add a file to the archive.
addFile :: FilePath   -- ^ Name of the file to create.
        -> ZipSource  -- ^ Source where file data is obtained from.
        -> Archive Int  -- ^ Position index of the new file.
addFile name src = do
  z <- getZip
  lift $ withCString name $ \name' -> do
    i <- c'zip_add z name' src
    if i < 0
       then c'zip_source_free src >> get_error z >>= E.throwIO
       else return $ fromIntegral i

-- | Add a directory to the archive.
addDirectory :: FilePath     -- ^ Directory's name in the archive.
             -> Archive Int  -- ^ Position index of the new directory entry.
addDirectory name = do
  z <- getZip
  r <- lift $ withCString name $ c'zip_add_dir z
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return (fromIntegral r)

-- | Replace a file in the archive.
replaceFile :: [FileFlag]  -- ^ Filename lookup mode.
            -> FilePath    -- ^ File to replace.
            -> ZipSource   -- ^ Source where the new file data is obtained from.
            -> Archive ()
replaceFile flags name src = do
  mbi <- nameLocate flags name
  maybe (lift $ c'zip_source_free src >> E.throwIO ErrNOENT)
        (\i -> replaceFileIx i src >> return ()) mbi

-- | Replace a file in the archive (referenced by position index).
replaceFileIx :: Int       -- ^ Position index of a file in the archive.
              -> ZipSource -- ^ Source where the new file data is obtained from
              -> Archive ()
replaceFileIx i src = do
  z <- getZip
  lift $ do
    r <- c'zip_replace z (fromIntegral i) src
    if r < 0
       then c'zip_source_free src >> get_error z >>= E.throwIO
       else return ()

-- | Create a data source. Note: input is converted to @[Word8]@ internally.
sourceBuffer :: (Enum a)
             => [a]
             -> Archive ZipSource
sourceBuffer src = do
  let ws = map (toEnum . fromEnum) src :: [Word8]
  z <- getZip
  lift $ withArrayLen ws $ \len buf -> do
      zs <- c'zip_source_buffer z (castPtr buf) (fromIntegral len) 0
      if zs == nullPtr
         then get_error z >>= E.throwIO
         else return zs

-- | Create a data source from a file.
sourceFile :: FilePath   -- ^ File to open.
           -> Int        -- ^ Offset from the beginning of the file.
           -> Int        -- ^ The number of bytes to read. If @0@ or @-1@,
                         -- the read till the end of file.
           -> Archive ZipSource
sourceFile name offset len = do
  z <- getZip
  lift $ withCString name $ \name' -> do
      zs <- c'zip_source_file z name' (fromIntegral offset) (fromIntegral len)
      if zs == nullPtr
         then get_error z >>= E.throwIO
         else return zs

-- | Create a data source from a file in the zip archive.
sourceZip :: [FileFlag]  -- ^ 'FileUNCHANGED' and 'FileRECOMPRESS' can be used.
          -> Zip         -- ^ Source archive.
          -> Int         -- ^ Position index of a file in the source archive.
          -> Int         -- ^ Offset from the beginning of the file.
          -> Int         -- ^ The number of bytes to read. If @0@ or @-1@,
                         -- then read till the end of file.
          -> Archive ZipSource
sourceZip flags srcz srcidx offset len = do
  z <- getZip
  lift $ do
    zs <- c'zip_source_zip z srcz (fromIntegral srcidx)
          (combine flags) (fromIntegral offset) (fromIntegral len)
    if zs == nullPtr
       then get_error z >>= E.throwIO
       else return zs

-- | Create a data source from a 'PureSource'.
-- Note: input of @[a]@ is converted to @[Word8]@ internally.
sourcePure :: (Enum a, Storable a, Storable st)
           => PureSource a st -> Archive ZipSource
sourcePure pureSrc = do
  z <- getZip
  lift $ do
    cb <- mk'zip_source_callback (runPureSource pureSrc)
    zs <- with (srcState pureSrc) $
          \pState -> c'zip_source_function z cb (castPtr pState)
    if zs == nullPtr
       then get_error z >>= E.throwIO
       else return zs

-- | Wrapper for a user-provided pure function to be used with 'sourcePure'.
-- Data size should be known in advance ('srcSize').
-- The function should support reading by chunks ('readSrc').
data (Enum a, Storable a, Storable st) => PureSource a st = PureSource {
    srcState :: st   -- ^ Initial state of the source.
  , srcSize  :: Int  -- ^ Total size of the data.
  , srcMTime :: Maybe UTCTime  -- ^ Modification time (current time if Nothing).
  , readSrc  :: Int -> st -> Maybe (Int, [a], st) -- ^ Read a chunk of the data,
                -- return @Just@ the size of data read, the data themselves and
                -- the new state of the source, or @Nothing@ on error.
  }

runPureSource :: (Enum a, Storable a, Storable st)
              => PureSource a st
              -> (Ptr () -> Ptr () -> CSize -> C'zip_source_cmd -> IO CSize)
runPureSource src pState pData len cmd
  | cmd == c'ZIP_SOURCE_OPEN = return 0
  | cmd == c'ZIP_SOURCE_READ = do
      state <- peek (castPtr pState :: Ptr st)
      case readSrc (src { srcState = state }) (fromIntegral len) state of
        Just (len',bs,state') -> do
          pokeArray (castPtr pData :: Ptr Word8) (map (toEnum.fromEnum) bs)
          poke (castPtr pState) state'
          return (fromIntegral len')
        Nothing -> return (-1)
  | cmd == c'ZIP_SOURCE_CLOSE = return 0
  | cmd == c'ZIP_SOURCE_STAT = do
      t <- maybe getCurrentTime return (srcMTime src)
      let pt = fromInteger . round . utcTimeToPOSIXSeconds $ t
      let pStat = castPtr pData
      c'zip_stat_init pStat
      stat <- peek pStat
      let stat' = stat { c'zip_stat'mtime = pt
                       , c'zip_stat'size = fromIntegral $ srcSize src }
      poke pStat stat'
      return $ fromIntegral (sizeOf stat')
  | cmd == c'ZIP_SOURCE_ERROR = do
      let pErrs = castPtr pData :: Ptr CInt
      poke pErrs (fromIntegral . fromEnum $ ErrINVAL)
      let (Errno esys) = eINVAL
      pokeElemOff pErrs 1 esys
      return $ fromIntegral (2 * sizeOf esys)
  | cmd == c'ZIP_SOURCE_FREE = return 0
  | otherwise = return (-1)
        
-- | Get zip archive comment.
getComment :: [FileFlag]  -- ^ 'FileUNCHANGED' can be used.
           -> Archive (Maybe String)
getComment flags = do
  z <- getZip
  (c,n) <- lift $ alloca $ \lenp -> do
         c <- c'zip_get_archive_comment z lenp (combine flags)
         n <- peek lenp
         return (c,n)
  if  c == nullPtr
    then return Nothing
    else lift $ peekCString c >>= return . Just . take (fromIntegral n)

-- | Set zip archive comment.
setComment :: String   -- ^ Comment message.
           -> Archive ()
setComment msg = do
  z <- getZip
  r <- lift $ withCStringLen msg $ \(msg',i') ->
       c'zip_set_archive_comment z msg' (fromIntegral i')
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Remove zip archive comment.
removeComment :: Archive ()
removeComment = do
  z <- getZip
  r <- lift $ c'zip_set_archive_comment z nullPtr 0
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Get comment for a file in the archive.
getFileComment :: [FileFlag]  -- ^ Filename lookup mode.
               -> FilePath    -- ^ Filename
               -> Archive (Maybe String)
getFileComment flags name = do
  mbi <- nameLocate flags name
  maybe (lift $ E.throwIO ErrNOENT) (getFileCommentIx flags) mbi

-- | Get comment for a file in the archive (referenced by position index).
getFileCommentIx :: [FileFlag]  -- ^ FileUNCHANGED can be used.
                 -> Int         -- ^ Position index of the file.
                 -> Archive (Maybe String)
getFileCommentIx flags i = do
  z <- getZip
  (c,n) <- lift $ alloca $ \lenp -> do
           c <- c'zip_get_file_comment z (fromIntegral i) lenp (combine flags)
           n <- peek lenp
           return (c,n)
  if c == nullPtr
     then return Nothing
     else lift $ peekCString c >>= return . Just . take (fromIntegral n)

-- | Set comment for a file in the archive.
setFileComment :: [FileFlag]   -- ^ Name lookup mode.
               -> FilePath     -- ^ Filename.
               -> String       -- ^ New file comment.
               -> Archive ()
setFileComment flags path comment = do
  mbi <- nameLocate flags path
  maybe (lift $ E.throwIO ErrNOENT) (flip setFileCommentIx comment) mbi

-- | Set comment for a file in the archive (referenced by position index).
setFileCommentIx :: Int        -- ^ Position index of a file in the archive.
                 -> String     -- ^ New file comment. 
                 -> Archive ()
setFileCommentIx i comment = do
  z <- getZip
  r <- lift $ withCStringLen comment $ \(msg,len) ->
       c'zip_set_file_comment z (fromIntegral i) msg (fromIntegral len)
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Remove comment for a file in the archive.
removeFileComment :: [FileFlag]  -- ^ Filename lookup mode.
                  -> FilePath    -- ^ Filename.
                  -> Archive ()
removeFileComment flags path = do
  mbi <- nameLocate flags path
  maybe (lift $ E.throwIO ErrNOENT) removeFileCommentIx mbi

-- | Remove comment for a file in the archive (referenced by position index).
removeFileCommentIx :: Int  -- ^ Position index of a file in the archive.
                    -> Archive ()
removeFileCommentIx i = do
  z <- getZip
  r <- lift $ c'zip_set_file_comment z (fromIntegral i) nullPtr 0
  if r < 0
     then lift $ get_error z >>= E.throwIO
     else return ()

-- | Undo changes to a file in the archive.
unchangeFile :: [FileFlag]  -- ^ Filename lookup mode.
             -> FilePath    -- ^ Filename.
             -> Archive ()
unchangeFile flags name = do
  mbi <- nameLocate flags name
  maybe (lift $ E.throw ErrNOENT) unchangeFileIx mbi

-- | Undo changes to a file in the archive (referenced by position index).
unchangeFileIx :: Int  -- ^ Position index of a file in the archive.
               -> Archive ()
unchangeFileIx i = do
  z <- getZip
  lift $ do
    r <- c'zip_unchange z (fromIntegral i)
    if r < 0
       then get_error z >>= E.throwIO
       else return ()

-- | Undo global changes to zip archive (revert changes to the archive
-- comment and global flags).
unchangeArchive :: Archive ()
unchangeArchive = do
  z <- getZip
  lift $ do
    r <- c'zip_unchange_archive z
    if r < 0
       then get_error z >>= E.throwIO
       else return ()

-- | Undo all changes in a zip archive.
unchangeAll :: Archive ()
unchangeAll = do
  z <- getZip
  lift $ do
    r <- c'zip_unchange_all z
    if r < 0
       then get_error z >>= E.throwIO
       else return ()

--
-- File reading operations
--

-- | Wrapper for operations with a file in the archive. 'fromFile' is normally
-- called from within an 'Archive' action (see also 'withArchive').
-- 'fromFile' can be replaced with 'fileContents' to read an entire file at
-- once.
fromFile :: [FileFlag]  -- ^ Filename lookup mode,
                        -- 'FileCOMPRESSED' and 'FileUNCHANGED' can be used.
         -> FilePath    -- ^ Name of the file in the arhive.
         -> Entry a     -- ^ Action with the file.
         -> Archive a
fromFile flags name action = do
    z <- getZip
    nameLocate flags name >>= maybe (lift $ get_error z >>= E.throwIO) runAction
  where
    runAction i = do
      z <- getZip
      zf <- lift $ withCString name $ \n -> c'zip_fopen z n (combine flags)
      if zf == nullPtr
        then lift $ get_error z >>= E.throwIO
        else do
          r <- fst `liftM` runStateT action (zf,i,flags)
          e <- lift $ c'zip_fclose zf
          if e /= 0
            then lift $ E.throwIO $ (toEnum . fromIntegral $ e :: ZipError)
            else return r

-- | Wrapper for operations with a file in the archive. File is referenced
-- by index (position). 'fromFileIx' is normally called from within
-- an 'Archive' action (see also 'withArchive'). 'fromFileIx' can be replaced
-- with 'fileContentsIx' to read an entire file at once.
fromFileIx :: [FileFlag] -- ^ 'FileCOMPRESSED' and 'FileUNCHANGED' can be used.
           -> Int        -- ^ Position index of a file in the archive.
           -> Entry a    -- ^ Action with the file.
           -> Archive a
fromFileIx flags i action = do
  z <- getZip
  zf <- lift $ c'zip_fopen_index z (fromIntegral i) (combine flags)
  if zf == nullPtr
     then lift $ get_error z >>= E.throwIO
     else do
       r <- fst `liftM` runStateT action (zf,i,flags)
       e <- lift $ c'zip_fclose zf
       if e /= 0
          then lift $ E.throwIO $ (toEnum . fromIntegral $ e :: ZipError)
          else return r

-- | Read at most @n@ bytes from the file.
readBytes ::
    (Enum a)
    => Int       -- ^ The number of bytes to read.
    -> Entry [a] -- ^ Bytes read.
readBytes n = do
  (zf,_,_) <- get
  lift . lift $ allocaArray n $ \buf -> do
         nread <- c'zip_fread zf (castPtr buf) (fromIntegral n)
         if nread < 0
            then
              get_file_error zf >>= E.throwIO
            else do
              bs <- peekArray (fromIntegral nread) buf :: IO [Word8]
              return . map (toEnum . fromEnum) $ bs

-- | Skip @n@ bytes from the open file. Note: this is not faster than reading.
skipBytes :: Int -> Entry ()
skipBytes n = (readBytes n :: Entry [Word8]) >> return ()

-- | Read entire file contents.
readContents ::
    (Enum a)
    => Entry [a]  -- ^ Contents of the file.
readContents = do
  (_,i,flags) <- get
  sz <- lift $ fileSizeIx flags i
  readBytes sz

-- | Read entire file. Shortcut for 'readContents' from within 'Archive' monad.
fileContents :: (Enum a)
    => [FileFlag]
    -> FilePath
    -> Archive [a]
fileContents flags name = fromFile flags name readContents

-- | Read entire file (referenced by position index). Shortcut for
-- 'readContents' from within 'Archive' monad.
fileContentsIx :: (Enum a)
    => [FileFlag]
    -> Int
    -> Archive [a]
fileContentsIx flags i = fromFileIx flags i readContents

--
-- Helpers
--

-- | Get archive handler. Throw 'ErrINVAL' if the archive is closed.
getZip :: Archive Zip
getZip = do
  z <- get
  if z == nullPtr
     then lift $ E.throwIO ErrINVAL
     else return z

-- | Get and throw a 'ZipError' if condition fails. Otherwise work normally.
doIf :: Bool -> Zip -> (Zip -> IO a) -> IO a
doIf cnd z action =
    if cnd
       then action z
       else get_error z >>= E.throwIO

-- | Get and throw a 'ZipError' if condition fails. See also 'doIf'.
doIf' :: Bool -> Zip -> (IO a) -> IO a
doIf' cnd z action = doIf cnd z (const action)
