packages feed

namecoin-update-0.2.3.0: src/Main.hs

-- | Tool to keep namecoin names updated and well
module Main where

import Control.Monad       (when)
import System.Environment  (getArgs)
import Namecoin            (Name(..), nameList, nameUpdate, uri)

import qualified Data.Text.IO as T


-- | Check whether a name is going to expire soon (~2 day)
isExpiring :: Name -> Bool
isExpiring name = expires_in name < 100

-- | Check for names that will expire soon and update them
nameCheck :: String -> IO ()
nameCheck uri = do
  names <- nameList uri
  case names of
    Left  error -> putStrLn ("Name check failed. "++error)
    Right names -> do
      putStrLn ("Found "++show (length names)++" names:")
      mapM (\i -> putStrLn $ " - "++name i) names

      let expiring = filter isExpiring names
          total    = length expiring
      if (total > 0) then do
        putStrLn (show total++" names are expiring")
        failed <- sum <$> mapM (nameUpdate uri) expiring
        if failed == 0
          then putStrLn "All names updated."
          else putStrLn (show failed ++ "/" ++ show total ++ " failed.")
      else
        putStrLn "Nothing to update."

-- | Main function
--
-- Reads the path of a namecoin config file
-- from the process arguments, connects to the
-- RPC server and updates the names found, if necessary.
main :: IO ()
main = do
  args <- getArgs
  when (null args) (fail "Must provide a namecoin config file.")
  conf <- T.readFile (head args)
  case uri conf of
    Left  err -> putStrLn ("Error reading config: " ++ err)
    Right uri -> nameCheck uri