module Hatch
( main
) where

import           Lens.Family ((^.))
import qualified System.Environment as Sys
import           System.FilePath ((</>))
import qualified System.FilePath as Sys
import qualified System.Exit as Sys
import qualified System.Posix.Process as Sys

import Config
import Types
import Util

main :: IO ()
main = do
  conf <- readConfig
  print (conf^.iniValueL)
  programName <- Sys.takeFileName `fmap` Sys.getProgName
  if programName == "hatch"
    then runAsHatch conf
    else runAsProxy conf programName


runAsProxy :: ConfigFile -> FilePath -> IO ()
runAsProxy conf program = do
  putStrLn ("Invoking as " ++ program)
  let ver = conf^.iniValueL.configCurrentCompiler
  case ver of
    Nothing -> Sys.die "No compiler configured!"
    Just c -> do
      let ver' = compilerString c
          root = conf^.iniValueL.configInstallPath </> ver'
          progn = root </> "bin" </> program
      args <- Sys.getArgs
      Sys.executeFile progn False args Nothing


data HatchCommand
  = SwitchCompiler
  | FetchCompiler
    deriving (Eq, Show)

runAsHatch :: ConfigFile -> IO ()
runAsHatch _ = do
  printErr "testing"
  putStrLn "Invoking as Hatch!"
