{-# LANGUAGE NoImplicitPrelude #-}
module Hc2Prosody.Password (
  Password(..), readPassword
) where

import BasicPrelude
import Data.ByteString (hGet, hPut)
import qualified Data.ByteString.Char8 as C
import Data.Machine (runT)
import Hc2Prosody.SecureFile (securelyOpenFile)
import System.IO.Machine

newtype Password = Password ByteString

toPassword :: ByteString -> Password
toPassword bs | '\n' `C.elem` bs = error "Password must not contain a newline character"
toPassword bs = Password bs

byBlock :: Int -> IODataMode ByteString
byBlock bytesPerBlock = ((`hGet` bytesPerBlock), hPut)

readPassword :: FilePath -> IO Password
readPassword filename = do
  h <- securelyOpenFile filename
  toPassword . mconcat <$> runT (sourceHandle (byBlock 65536) h)