namecoin-update/Main.hs

54 lines
1.5 KiB
Haskell
Raw Normal View History

2015-05-12 23:09:23 +02:00
{-# Language TemplateHaskell, RecordWildCards #-}
2015-04-19 23:36:44 +02:00
import System.Process
import System.Exit
2017-01-26 23:50:27 +01:00
import System.Environment (getArgs)
import Data.Maybe (listToMaybe, fromMaybe)
2015-04-19 23:36:44 +02:00
import Data.Aeson
2015-05-12 23:09:23 +02:00
import Data.Aeson.TH
2015-04-19 23:36:44 +02:00
import Data.ByteString.Lazy.Char8 (pack)
2016-08-29 06:07:56 +02:00
import Control.Exception (try)
2015-04-19 23:36:44 +02:00
2016-08-29 06:07:56 +02:00
data Name = Name
{ name :: String
, value :: String
, expires_in :: Int
}
2015-04-19 23:36:44 +02:00
2015-05-12 23:09:23 +02:00
deriveJSON defaultOptions ''Name
2015-04-19 23:36:44 +02:00
2016-08-29 06:07:56 +02:00
2017-01-26 23:50:27 +01:00
defaultPath :: FilePath
defaultPath = "$XDG_CONFIG_HOME/namecoin"
2016-08-29 06:07:56 +02:00
2017-01-26 23:50:27 +01:00
namecoin :: FilePath -> [String] -> CreateProcess
namecoin path args = shell ("namecoind -conf=" ++ path ++ " " ++ unwords args)
2016-08-29 06:07:56 +02:00
2017-01-26 23:50:27 +01:00
readCommand conf = readCreateProcess (namecoin conf ["name_list"]) ""
updateCommand conf n v = readCreateProcessWithExitCode (namecoin conf ["name_update", n, v]) ""
updateName :: FilePath -> Name -> IO Int
updateName conf Name{..}
2015-04-19 23:36:44 +02:00
| expires_in < 100 = do
2017-01-26 23:50:27 +01:00
(code, out, err) <- updateCommand conf name value
2015-04-19 23:36:44 +02:00
if code == ExitSuccess
then putStrLn (name ++ " updated: " ++ out) >> return 0
else putStrLn (name ++ " update failed: " ++ err) >> return 1
| otherwise = putStrLn ("No need to update " ++ name) >> return 0
2016-08-29 06:07:56 +02:00
2015-04-19 23:36:44 +02:00
main :: IO ()
main = do
2017-01-26 23:50:27 +01:00
conf <- (fromMaybe defaultPath . listToMaybe) <$> getArgs
out <- pack <$> readCommand conf
2015-04-19 23:36:44 +02:00
case eitherDecode out of
Right names -> do
2017-01-26 23:50:27 +01:00
errs <- sum <$> mapM (updateName conf) (names :: [Name])
2015-04-19 23:36:44 +02:00
if errs > 0
then putStrLn (show errs ++ " updates failed")
2016-08-29 06:07:56 +02:00
else putStrLn "All ok"
2017-01-26 23:50:27 +01:00
Left err -> putStrLn ("Error communicating with namecoin: " ++ err)