module Network.API.TheMovieDB.Util (loadKey, loadContext) where
import Prelude hiding (catch)
import Control.Exception (catch)
import Control.Monad (liftM, msum)
import Data.Char (isSpace)
import Network.API.TheMovieDB.HTTP
import Network.API.TheMovieDB.Types
import System.Environment (getEnv)
import System.IO.Error (isDoesNotExistError)
import System.Posix.Files
import System.Posix.User
getEnvMaybe :: String -> IO (Maybe String)
getEnvMaybe n = env `catch` err
where env = liftM Just $ getEnv n
err e = if isDoesNotExistError e
then return Nothing
else ioError e
expandFile :: FilePath -> IO FilePath
expandFile ('~':rest) = do userID <- getEffectiveUserID
entry <- getUserEntryForID userID
return $ homeDirectory entry ++ rest
expandFile dir = return dir
readFileMaybe :: FilePath -> IO (Maybe String)
readFileMaybe n = do realName <- expandFile n
exists <- fileExist realName
if exists
then liftM Just (readFirstLine realName)
else return Nothing
where readFirstLine = liftM skipSpace . readFile
skipSpace = filter $ not . isSpace
loadKey :: IO (Maybe Key)
loadKey = liftM msum . sequence $ [env, xdgConfig, config, home]
where env = getEnvMaybe "TMDB_KEY"
config = readFileMaybe "~/.config/tmdbkey"
home = readFileMaybe "~/.tmdbkey"
xdgConfig = do dir <- getEnvMaybe "XDG_CONFIG_HOME"
case dir of
Nothing -> return Nothing
Just d -> readFileMaybe (d ++ "/tmdbkey")
loadContext :: IO (Maybe Context)
loadContext = liftM (fmap mkContext) loadKey