module Main where

import System.Environment
import Data.Maybe (fromMaybe)
import Control.Monad (when)
import Control.Monad.Except
import System.IO
import System.Exit
import System.Directory
import Control.Exception (try, SomeException)

import VersionManager as VM
import App
import Server
import Config

empty :: App -> IO ()
empty app =
  do  when (help . flags $ app) (putStrLn usageApp >> exitSuccess)
      when (version . flags $ app) (putStrLn "Det 0.1.0" >> exitSuccess)
      failWithUsage ["Missing Command\n"]

run :: App -> IO ()
run app = case action app of
  Config      -> Config.config app
  Cluster     -> Config.cluster app
  Start       -> Server.run app pull
  Init        -> VM.init app
  Commit      -> VM.commit app
  Diff        -> VM.diff app
  History     -> VM.history app
  Rollback    -> VM.rollback app
  Empty       -> empty app
  _           -> print app

main :: IO ()
main =
  do  path <- fromMaybe ("~/.det") <$> lookupEnv "DET_PATH"
      setEnv "DET_PATH" path
      err <-  try (compileApp >>= Main.run)
              :: IO (Either SomeException ())

      case err of
        Left e  ->
          do  hPutStrLn stderr "Error:"
              hPutStrLn stderr (show e)
        _       -> return ()
