{-# LANGUAGE FlexibleInstances  #-}
{-# LANGUAGE OverloadedStrings  #-}
module Main where

import           Control.Monad.Except (runExceptT)
import           Data.Monoid ((<>))
import           Options.Applicative (Parser, execParser, strOption, long, value, info, helper, fullDesc)
import           System.Exit (exitWith, ExitCode(..))
import           Network.Wai.Handler.Warp (run)

import           Config

import           WebApp

main :: IO ()
main = do
    cfg <- execParser opts >>= runExceptT . loadConfig
    case cfg of
        Left err -> print err >> exitWith (ExitFailure 1)
        Right cfg_ -> do
            print cfg_
            ctx <- newContext cfg_
            case ctx of
                Left err -> print err >> exitWith (ExitFailure 1)
                Right ctx_ -> run (port cfg_) (webapp ctx_)
  where
    opts = info (helper <*> cliOptions) fullDesc


cliOptions :: Parser FilePath
cliOptions = strOption (long "config" <> value "config.yml")

