{-# LANGUAGE OverloadedStrings #-}
module Main where

import Control.Applicative
import Control.Monad
import Data.Maybe
import qualified Network.Wai.Handler.Warp as Warp
import qualified Waldo.StoryExample as SE
import Waldo.Waldo
import Waldo.Server
import System.Environment
import Network.Wai.UrlMap
import Network.Wai.Application.Static
import WaiAppStatic.Types (unsafeToPiece)
import Safe

import Paths_waldo

main :: IO ()
main = do
    env <- getEnvironment
    case lookup "WALDO_DATA" env of
      Nothing -> do
        putStrLn "Please set WALDO_DATA to a directory containing:"
        putStrLn " - full_php_browscap.ini"
        putStrLn " - GeoIPCity.dat"
        putStrLn " - GeoIPNet.dat"
        putStrLn " - GeoIPNet.dat"
        putStrLn " - GeoIPOrg.dat"
      Just dd -> do
        -- This is where we "load" a set of scripts to serve.      
        -- Conceptually the server can serve any number of scripts.
        wdata <- loadWaldo dd [("jarUcyikAg3", SE.loadScriptGen)]
        bp <- getDataDir
        Warp.runSettings (warpsettings env) . mapUrls $
              mount "story" (waldoApp wdata)
          <|> mount "loadedPanels" ((staticApp (defaultFileServerSettings "/tmp/loadedPanels") {ssIndices=[unsafeToPiece "testcomic.html"]}))
          <|> mountRoot (staticApp (defaultFileServerSettings bp))
  where
    warpsettings env = Warp.setPort (fromMaybe 3000 (join $ fmap readMay $ lookup "WALDO_PORT" env)) Warp.defaultSettings
