-- with gracious thanks to mightybyte:
-- http://softwaresimply.blogspot.com/2008_02_01_archive.html

module Main where
import Happstack.Server hiding (port)
import Happstack.State
import Controller
import System.Environment
import StateVersions.AppState1
import Happstack.Server.Helpers

main :: IO ()
main = do
  args <- getArgs -- getArgs is from System.Environment, if you're not familiar with it
  case args of
    [port, dynamicTemplateReload', allowStressTests'] -> do
       let p = read port
           allowStressTests = read allowStressTests'
           dynamicTemplateReload = read dynamicTemplateReload'
       --cleanUpLockFile "happs-tutorial" "tutorial.happstack.com" "happstack" 5
       tDirGroups <- getTemplateGroups -- defined in Controller.hs
       {- smartserver and its cousin smartserver' are from the happstack-helpers package.
          They are essentially a combination startSystemState and simpleHTTP('), with a
          few other minor conveniences built in.

          Just like with simpleHTTP we pass in the ServerPartT, given by controller from Controller.hs,
          and just like startSystemState we pass in a Proxy in order to initialize the system state.
        -}
       smartserver (Conf p Nothing) 
                    (controller tDirGroups dynamicTemplateReload allowStressTests)
                    stateProxy
    _ -> putStrLn "usage example: happs-tutorial 5001 True True (starts the app on port 5001, \
                      \templates reload dynamically on every request, allows stress tests)"

runInGhci :: IO ()
runInGhci = do
    putStrLn $ "happs tutorial running in ghci. \n" ++
             "exit :q ghci completely and reenter ghci, before restarting."
    tDirGroups <- getTemplateGroups
    smartserver (Conf 5001 Nothing) (controller tDirGroups True True) stateProxy

stateProxy :: Proxy AppState
stateProxy = Proxy
