alea/main.hs

55 lines
1.6 KiB
Haskell
Raw Normal View History

2014-12-12 22:13:55 +01:00
{-# LANGUAGE RecordWildCards #-}
2014-10-13 21:26:55 +02:00
import System.IO
2014-12-12 22:14:34 +01:00
import System.Console.ArgParser
import Control.Monad
import Control.Applicative
2014-10-13 21:26:55 +02:00
2014-10-14 00:40:42 +02:00
import Paths_alea (getDataFileName)
2014-10-14 19:14:44 +02:00
import Alea.Diceware
import Alea.Random
2014-10-13 21:26:55 +02:00
2014-12-12 22:13:55 +01:00
data ProgArgs = ProgArgs
2014-10-13 21:26:55 +02:00
{ interactive :: Bool
, dictionary :: FilePath
, phraseLength :: Int
, phrases :: Int
2014-12-12 22:13:55 +01:00
} deriving (Show)
2014-10-13 21:26:55 +02:00
2014-12-12 22:13:55 +01:00
parser :: IO (ParserSpec ProgArgs)
parser = path >>= \path -> return $ ProgArgs
`parsedBy` boolFlag "interactive" `Descr` "Manually insert numbers"
`andBy` optFlag path "dictionary" `Descr` "Specify dictionary file path"
`andBy` optFlag 6 "lenght" `Descr` "Number of words in a passphrase"
`andBy` optFlag 1 "phrases" `Descr` "Number of passphrases to generate"
2014-10-13 21:26:55 +02:00
2014-12-12 22:13:55 +01:00
interface :: IO (CmdLnInterface ProgArgs)
interface =
(`setAppDescr` "A diceware passphrase generator") <$>
(`setAppEpilog` "Alea iacta est.") <$>
(mkApp =<< parser)
2014-10-13 21:26:55 +02:00
main :: IO ()
2014-12-12 22:14:34 +01:00
main = interface >>= flip runApp (readDict >=> exec)
2014-10-14 19:14:44 +02:00
2014-12-12 22:14:34 +01:00
-- Default path of the dictionary
path :: IO FilePath
path = getDataFileName "dict/diceware"
-- Read dictionary file
readDict :: ProgArgs -> IO ProgArgs
readDict args@ProgArgs{..} =
readFile dictionary >>= \x -> return args {dictionary = x}
2014-10-13 21:26:55 +02:00
-- Main function
2014-12-12 22:13:55 +01:00
exec :: ProgArgs -> IO ()
exec args@ProgArgs{..} =
2014-10-13 21:26:55 +02:00
if interactive
2014-12-12 22:14:34 +01:00
then interact (unlines . map dice . lines)
else do
randWords dictSize phraseLength >>= putStrLn . unwords . map dice'
when (phrases > 1) $ exec args {phrases = phrases - 1}
2014-10-13 21:26:55 +02:00
where
2014-12-12 22:14:34 +01:00
(dict, dictSize) = (parseDiceware dictionary, length dict)
dice n = readDiceware dict (read n :: Int)
dice' n = readDiceware' dict n