propellor/Propellor/PrivData.hs

78 lines
1.9 KiB
Haskell
Raw Normal View History

2014-03-31 03:37:54 +00:00
module Propellor.PrivData where
2014-03-30 23:11:24 +00:00
import qualified Data.Map as M
import Control.Applicative
import System.FilePath
import System.IO
import System.Directory
import Data.Maybe
import Control.Monad
2014-03-31 03:37:54 +00:00
import Propellor.Types
2014-03-31 22:31:08 +00:00
import Propellor.Message
2014-03-30 23:11:24 +00:00
import Utility.Monad
import Utility.PartialPrelude
import Utility.Exception
import Utility.Process
import Utility.Tmp
import Utility.SafeCommand
2014-03-31 01:01:18 +00:00
import Utility.Misc
2014-03-30 23:11:24 +00:00
withPrivData :: PrivDataField -> (String -> IO Result) -> IO Result
withPrivData field a = maybe missing a =<< getPrivData field
where
missing = do
2014-03-31 00:23:23 +00:00
warningMessage $ "Missing privdata " ++ show field
2014-03-30 23:11:24 +00:00
return FailedChange
getPrivData :: PrivDataField -> IO (Maybe String)
getPrivData field = do
m <- catchDefaultIO Nothing $ readish <$> readFile privDataLocal
return $ maybe Nothing (M.lookup field) m
2014-03-31 01:01:18 +00:00
setPrivData :: HostName -> PrivDataField -> IO ()
setPrivData host field = do
putStrLn "Enter private data on stdin; ctrl-D when done:"
2014-04-01 22:42:32 +00:00
value <- chomp <$> hGetContentsStrict stdin
2014-03-30 23:19:29 +00:00
makePrivDataDir
2014-03-30 23:11:24 +00:00
let f = privDataFile host
m <- fromMaybe M.empty . readish <$> gpgDecrypt f
let m' = M.insert field value m
gpgEncrypt f (show m')
2014-03-31 01:01:18 +00:00
putStrLn "Private data set."
2014-03-30 23:11:24 +00:00
void $ boolSystem "git" [Param "add", File f]
2014-04-01 22:42:32 +00:00
where
chomp s
| end s == "\n" = chomp (beginning s)
| otherwise = s
2014-03-30 23:11:24 +00:00
2014-03-30 23:19:29 +00:00
makePrivDataDir :: IO ()
makePrivDataDir = createDirectoryIfMissing False privDataDir
2014-03-30 23:11:24 +00:00
privDataDir :: FilePath
privDataDir = "privdata"
privDataFile :: HostName -> FilePath
privDataFile host = privDataDir </> host ++ ".gpg"
privDataLocal :: FilePath
privDataLocal = privDataDir </> "local"
gpgDecrypt :: FilePath -> IO String
gpgDecrypt f = ifM (doesFileExist f)
( readProcess "gpg" ["--decrypt", f]
, return ""
)
gpgEncrypt :: FilePath -> String -> IO ()
gpgEncrypt f s = do
encrypted <- writeReadProcessEnv "gpg"
[ "--default-recipient-self"
, "--armor"
, "--encrypt"
]
Nothing
(Just $ flip hPutStr s)
Nothing
viaTmp writeFile f encrypted