module GitHUD.Debug (
  debug,
  debugOnStderr
  ) where

import Control.Monad (when)
import Data.Maybe (fromMaybe)
import System.Environment (lookupEnv)
import System.IO (stdout, stderr, hFlush, hPutStrLn)

debugEnvVar :: String
debugEnvVar :: String
debugEnvVar = String
"GITHUD_DEBUG"

debugEnvVarValue :: String
debugEnvVarValue :: String
debugEnvVarValue = String
"TRUE"

isDebugActive :: IO Bool
isDebugActive :: IO Bool
isDebugActive = do
  Maybe String
env <- String -> IO (Maybe String)
lookupEnv String
debugEnvVar
  let debug :: String
debug = String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe String
"FALSE" Maybe String
env
  Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool -> IO Bool) -> Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ String
debug String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
debugEnvVarValue

whenDebugActive :: IO () -> IO ()
whenDebugActive :: IO () -> IO ()
whenDebugActive IO ()
effect = do
  Bool
debugActive <- IO Bool
isDebugActive
  if Bool
debugActive then IO ()
effect else () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

debug :: String
      -> IO ()
debug :: String -> IO ()
debug String
msg = IO () -> IO ()
whenDebugActive (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  String -> IO ()
putStrLn String
msg
  Handle -> IO ()
hFlush Handle
stdout

debugOnStderr :: String
              -> IO ()
debugOnStderr :: String -> IO ()
debugOnStderr String
msg = IO () -> IO ()
whenDebugActive (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  Handle -> String -> IO ()
hPutStrLn Handle
stderr String
msg
  Handle -> IO ()
hFlush Handle
stderr