module Common
(
defaultCredsFile
,toCredsFile
,parseCredsFile
)where
import System.IO.Unsafe (unsafePerformIO)
import System.Environment (getEnv)
import Text.Printf (printf)
import qualified Network.Asus.WL500gP as W
import Data.Char (toLower)
import Control.Monad (liftM)
import System.Directory (getAppUserDataDirectory, createDirectoryIfMissing)
import System.FilePath ((</>))
appName = "WL500gPControl"
appConfDir = getAppUserDataDirectory appName
initConfDir = appConfDir >>= createDirectoryIfMissing True
defaultCredsFile = liftM (</> "credentials") appConfDir
toCredsFile :: Maybe String -> IO String
toCredsFile Nothing = defaultCredsFile
toCredsFile (Just f) = return f
parseCredsFile :: Maybe String -> IO (Maybe W.Connection)
parseCredsFile Nothing = do
initConfDir >> defaultCredsFile >>= parseCredsFile . Just
parseCredsFile (Just fname) =
let toPair (a:b:[]) = (map toLower a, b)
toPair _ = ("", "")
parse = filter (/= ("", "")) . map (toPair . words) . lines
in do
contentsMap <- liftM parse $ readFile fname
return $ do (host:passwd:user:[]) <-
mapM (`lookup` contentsMap) ["host:"
,"password:"
,"user:"]
return $ W.Connection {W.user = user
,W.password = passwd
,W.hostname = host}