-- A simple unzip utility.
--
-- This is an example of using legacy LibZip-0.0 API.
--
module Main where

import qualified Data.ByteString as B
import Control.Monad (forM_,when)
import System.Directory (createDirectoryIfMissing)
import System.Environment (getArgs)
import System.FilePath (takeDirectory)

import Codec.Archive.LibZip

usage = "unzip [-l] file.zip [files]"

main = do
  args <- getArgs
  let onlyList = "-l" `elem` args
  let args' = filter (/= "-l") args
  case args' of
    [] -> putStrLn usage
    (filename:files) -> do
      catchZipError $
        withZip filename [] $ \z -> do
          files' <- getFiles z []
          forM_ files' $ \f -> do
            when (f `elem` files || null files) $
              if onlyList
                then putStrLn f
                else saveFile f =<< readZipFile z f []
      $ \e -> putStrLn $ "Error in " ++ filename ++ ": " ++ show e

saveFile f contents = do
  if isDir f
    then createDirectoryIfMissing True $ takeDirectory f
    else B.writeFile f contents

