{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NoImplicitPrelude #-}

-- | A general purpose build tool.
--
-- : out bild
-- : dep docopt
-- : dep regex-applicative
-- : dep rainbow
-- : dep tasty
-- : dep tasty-hunit
--
-- == Design constraints
--
--    * only input is one or more a namespaces. no subcommands, no packages
--
--    * no need to write specific build rules
--
--        * one rule for hs, one for rs, one for scm, and so on
--
--        * rules are written in Haskell as much as possible
--
--    * no need to distinguish between exe and lib, just have a single output
--
--    * never concerned with deployment/packaging - leave that to another tool
--      (scp? tar?)
--
-- == Features
--
--    * namespace maps to filesystem
--
--        * no need for `bild -l` for listing available targets.
--          Use `ls` or `tree`
--
--        * you build namespaces, not files/modules/packages/etc
--
--    * namespace maps to language modules
--
--        * build settings can be set in the file comments
--
--    * pwd is always considered the the source directory,
--      no `src` vs `doc` etc.
--
--    * build methods automaticatly detected with file extensions
--
--    * flags modify the way to interact with the build, some ideas:
--
--        * -s = jump into a shell and/or repl
--
--        * -p = turn on profiling
--
--        * -t = limit build by type (file extension)
--
--        * -e = exclude some regex in the ns tree
--
--        * -o = optimize level
--
-- == Example Commands
--
-- > bild [opts] <target..>
--
-- The general scheme is to build the things described by the targets. A target
-- is a namespace. You can list as many as you want, but you must list at least
-- one. It could just be `.` for the current directory. Build outputs will go
-- into the _/bild directory in the root of the project.
--
-- > bild A/B.hs
--
-- This will build the file at ./A/B.hs, which translates to something like
-- `ghc --make A.B`.
--
-- > bild -s <target>
--
-- Starts a repl/shell for target.
--  - if target.hs, load ghci
--  - if target.scm, load scheme repl
--  - if target.clj, load a clojure repl
--  - if target.nix, load nix-shell
--  - and so on.
--
-- > bild -p <target>
--
-- build target with profiling (if available)
--
-- > bild -t nix target
--
-- only build target.nix, not target.hs and so on (in the case of multiple
-- targets with the same name but different extension).
--
-- == Build Metadata
--
-- Metadata is set in the comments with a special syntax. For third-party deps,
-- we list the deps in comments in the target file, like:
--
-- > -- : dep aeson
--
-- The output executable is named with:
--
-- > -- : out my-program
--
-- or
--
-- > -- : out my-ap.js
--
-- When multiple compilers are possible (e.g. ghc vs ghcjs) we use the @out@
-- extension, for example we chose ghcjs when the target @out@ ends in .js. If
-- @out@ does not have an extension, each build type falls back to a default,
-- usually an executable binary.
--
-- This method of setting metadata in the module comments works pretty well,
-- and really only needs to be done in the entrypoint module anyway.
--
-- Local module deps are included by just giving the repo root to the underlying
-- compiler for the target, and the compiler does work of walking the source
-- tree.
module Biz.Bild where

import Alpha hiding (sym, (<.>))
import qualified Biz.Cli as Cli
import Biz.Namespace (Namespace (..))
import qualified Biz.Namespace as Namespace
import Biz.Test ((@=?))
import qualified Biz.Test as Test
import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.String as String
import qualified Data.Text as Text
import Rainbow (Chunk, chunk, fore, green, putChunkLn, red)
import qualified System.Directory as Dir
import qualified System.Environment as Env
import qualified System.Exit as Exit
import System.FilePath ((</>))
import qualified System.Process as Process
import qualified Text.Regex.Applicative as Regex
import qualified Prelude

main :: IO ()
main = Cli.main <| Cli.Plan help move test
  where
    test = Test.group "Biz.Bild" [Test.unit "id" <| 1 @=? (1 :: Integer)]
    move args =
      mapM getNamespace (Cli.getAllArgs args (Cli.argument "target"))
        /> catMaybes
        /> filter isBuildableNs
        >>= mapM analyze
        >>= mapM
          ( build
              (args `Cli.has` Cli.longOption "test")
              (args `Cli.has` Cli.longOption "loud")
          )
        >>= exitSummary

help :: Cli.Docopt
help =
  [Cli.docopt|
bild

Usage:
  bild test
  bild --help
  bild [--test] [--loud]  <target>...

Options:
  --test  Run tests on a target after building.
  --loud  Show all output from compiler.
  --help  Print this info
|]

exitSummary :: [Exit.ExitCode] -> IO ()
exitSummary exits =
  if failures > 0
    then Exit.die <| show failures
    else Exit.exitSuccess
  where
    failures = length <| filter isFailure exits

type Dep = String

type Out = String

data Compiler
  = GhcLib
  | GhcExe
  | GhcjsLib
  | GhcjsExe
  | Guile
  | NixBuild
  | Copy
  deriving (Show)

data Target = Target
  { -- | Output name
    out :: Out,
    -- | Fully qualified namespace partitioned by '.'
    namespace :: Namespace,
    -- | Absolute path to file
    path :: FilePath,
    -- | Parsed/detected dependencies
    deps :: [Dep],
    -- | Which compiler should we use?
    compiler :: Compiler,
    -- | Where is this machine being built? Schema: user@location
    builder :: String
  }
  deriving (Show)

isBuildableNs :: Namespace -> Bool
isBuildableNs (Namespace _ Namespace.Hs) = True
isBuildableNs ns
  | ns `elem` nixTargets = True
  | otherwise = False

nixTargets :: [Namespace]
nixTargets =
  [ Namespace ["Biz", "Pie"] Namespace.Nix,
    Namespace ["Biz", "Que", "Prod"] Namespace.Nix,
    Namespace ["Biz", "Cloud"] Namespace.Nix,
    Namespace ["Biz", "Dev"] Namespace.Nix,
    Namespace ["Hero", "Prod"] Namespace.Nix
  ]

getNamespace :: String -> IO (Maybe Namespace)
getNamespace s = do
  root <- Env.getEnv "BIZ_ROOT"
  cwd <- Dir.getCurrentDirectory
  return <| Namespace.fromPath root <| cwd </> s

analyze :: Namespace -> IO Target
analyze namespace@(Namespace.Namespace _ ext) = do
  user <- Env.getEnv "USER"
  host <- chomp </ readFile "/etc/hostname"
  let path = Namespace.toPath namespace
  case ext of
    Namespace.Hs -> do
      content <- String.lines </ Prelude.readFile path
      let out =
            content
              /> Regex.match metaOut
              |> catMaybes
              |> head
              |> fromMaybe mempty
      let compiler = detectGhcCompiler out <| String.unlines content
      return
        Target
          { deps = content /> Regex.match metaDep |> catMaybes,
            builder = user <> "@localhost",
            ..
          }
    Namespace.Nix ->
      return
        Target
          { deps = [],
            compiler = NixBuild,
            out = "",
            builder =
              if host == "lithium"
                then mempty
                else
                  join
                    [ "ssh://",
                      user,
                      "@dev.simatime.com?ssh-key=/home/",
                      user,
                      "/.ssh/id_rsa"
                    ],
            ..
          }
    Namespace.Scm ->
      return
        Target
          { deps = [],
            compiler = Guile,
            out = "",
            builder = user <> "@localhost",
            ..
          }
    _ ->
      return
        Target
          { deps = [],
            compiler = Copy,
            out = "",
            builder = user <> "@localhost",
            ..
          }

-- | Some rules for detecting the how to compile a ghc module. If there is an
-- out, then we know it's some Exe; if the out ends in .js then it's GhcjsExe,
-- otherwise GhcExe. That part is solved.
--
-- Detecting a Lib is harder, and much code can be compiled by both ghc and
-- ghcjs. For now I'm just guarding against known ghcjs-only modules in the
-- import list.
detectGhcCompiler :: String -> String -> Compiler
detectGhcCompiler out _ | jsSuffix out = GhcjsExe
detectGhcCompiler out _ | not <| jsSuffix out || null out = GhcExe
detectGhcCompiler _ content
  | match "import GHCJS" = GhcjsLib
  | otherwise = GhcLib
  where
    match s = s `List.isInfixOf` content

jsSuffix :: String -> Bool
jsSuffix = List.isSuffixOf ".js"

isFailure :: Exit.ExitCode -> Bool
isFailure (Exit.ExitFailure _) = True
isFailure Exit.ExitSuccess = False

build :: Bool -> Bool -> Target -> IO Exit.ExitCode
build andTest loud target@Target {..} = do
  root <- Env.getEnv "BIZ_ROOT"
  case compiler of
    GhcExe -> do
      putStrLn <| "bild:  dev:  ghc-exe: " <> Namespace.toPath namespace
      let outDir = root </> "_/bild/dev/bin"
      Dir.createDirectoryIfMissing True outDir
      putText <| "bild:  dev:  bilder: " <> Text.pack builder
      exitcode <-
        proc
          loud
          "ghc"
          [ "-Werror",
            "-i" <> root,
            "-odir",
            root </> "_/bild/int",
            "-hidir",
            root </> "_/bild/int",
            "--make",
            path,
            "-main-is",
            Namespace.toHaskellModule namespace,
            "-o",
            outDir </> out
          ]
      putChunkLn <| fore green <| "bilt:  " <> nschunk namespace
      when andTest <| do
        Process.readProcessWithExitCode (outDir </> out) ["test"] "" >>= \case
          (Exit.ExitSuccess, _, _) ->
            putChunkLn <| fore green <| "test:  " <> nschunk namespace
          (Exit.ExitFailure _, stdout_, stderr_) -> do
            putChunkLn <| fore red <| "test:  " <> nschunk namespace
            when (stdout_ /= mempty) <| putStr stdout_
            when (stderr_ /= mempty) <| putStr stderr_
      return exitcode
    GhcLib -> do
      putStrLn <| "bild:  dev:  ghc-lib: " <> Namespace.toPath namespace
      putText <| "bild:  dev:  bilder: " <> Text.pack builder
      exitcode <-
        proc
          loud
          "ghc"
          [ "-Werror",
            "-i" <> root,
            "-odir",
            root </> "_/bild/int",
            "-hidir",
            root </> "_/bild/int",
            "--make",
            path
          ]
      putChunkLn <| fore green <| "bilt:  " <> nschunk namespace
      return exitcode
    GhcjsExe -> do
      putStrLn <| "bild:  dev:  ghcjs-exe: " <> Namespace.toPath namespace
      let outDir = root </> "_/bild/dev/static"
      Dir.createDirectoryIfMissing True outDir
      putText <| "bild:  dev:  local: " <> Text.pack builder
      exitcode <-
        proc
          loud
          "ghcjs"
          [ "-Werror",
            "-i" <> root,
            "-odir",
            root </> "_/bild/int",
            "-hidir",
            root </> "_/bild/int",
            "--make",
            path,
            "-main-is",
            Namespace.toHaskellModule namespace,
            "-o",
            outDir </> out
          ]
      putChunkLn <| fore green <| "bilt:  " <> nschunk namespace
      return exitcode
    GhcjsLib -> do
      putStrLn <| "bild:  dev:  ghcjs-lib: " <> Namespace.toPath namespace
      putText <| "bild:  dev:  local: " <> Text.pack builder
      exitcode <-
        proc
          loud
          "ghcjs"
          [ "-Werror",
            "-i" <> root,
            "-odir",
            root </> "_/bild/int",
            "-hidir",
            root </> "_/bild/int",
            "--make",
            path
          ]
      putChunkLn <| fore green <| "bilt:  " <> nschunk namespace
      return exitcode
    Guile -> do
      putStrLn <| "bild:  dev:  guile: " <> Namespace.toPath namespace
      putText <| "bild:  dev:  local: " <> Text.pack builder
      putText "bild:  guile:  TODO"
      putText <| show target
      return Exit.ExitSuccess
    NixBuild -> do
      putStrLn <| "bild:  nix:  " <> Namespace.toPath namespace
      let outDir = root </> "_/bild/nix"
      Dir.createDirectoryIfMissing True outDir
      if null builder
        then putText <| "bild:  nix:  local"
        else
          putText <| "bild:  nix:  remote: "
            <> Text.pack builder
      exitcode <-
        proc
          loud
          "nix-build"
          [ path,
            "-o",
            outDir </> Namespace.toPath namespace,
            -- Set default arguments to nix functions
            "--arg",
            "bild",
            "import " <> root
              </> "Biz/Bild/Rules.nix"
              <> " { nixpkgs = import "
              <> root
              </> "Biz/Bild/Nixpkgs.nix"
              <> "; }",
            "--arg",
            "lib",
            "(import " <> root </> "Biz/Bild/Nixpkgs.nix).lib",
            "--builders",
            builder
          ]
      putChunkLn <| fore green <| "bilt:  " <> nschunk namespace
      return exitcode
    Copy -> do
      putStrLn <| "bild:  copy:  " <> Namespace.toPath namespace
      putText "bild:  copy:  TODO"
      putText <| show target
      return Exit.ExitSuccess

-- | Run a subprocess, handling output appropriately.
proc :: Bool -> String -> [String] -> IO Exit.ExitCode
proc loud cmd args = do
  (exitcode, stdout_, stderr_) <- Process.readProcessWithExitCode cmd args ""
  when loud <| putStr <| stdout_ ++ stderr_
  when (isFailure exitcode) <| putStr <| stdout_ ++ stderr_
  return exitcode

nschunk :: Namespace -> Chunk
nschunk = chunk <. Text.pack <. Namespace.toPath

metaDep :: Regex.RE Char Dep
metaDep = Regex.string "-- : dep " *> Regex.many (Regex.psym Char.isAlpha)

metaOut :: Regex.RE Char Out
metaOut = Regex.string "-- : out " *> Regex.many (Regex.psym (/= ' '))