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

-- | A general purpose build tool.
--
-- Not all of the below design is implemented. Currently:
--
-- - with a nix build, results are linked in _/bild/nix/<target>
-- - with a dev build, results are stored in _/bild/dev/<target>
--
-- -----------------------------------------------------------------------------
--
-- == Design constraints
--
--    * only input is a namespace, no subcommands, no packages
--
--    * no need to write specific build rules
--
--        * one rule for hs, one for rs, one for scm, and so on
--
--    * 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 Data.Char as Char
import qualified Data.List as List
import qualified Data.String as String
import qualified Data.Text as Text
import qualified System.Directory as Dir
import qualified System.Environment as Env
import qualified System.Exit as Exit
import System.FilePath ((</>))
import qualified System.FilePath as File
import qualified System.Process as Process
import qualified Text.Regex.Applicative as Regex
import qualified Prelude

main :: IO ()
main =
  Env.getArgs /> head >>= \case
    Nothing -> Exit.die "usage: bild <target>"
    Just target -> analyze target >>= build

type Namespace = String

type Dep = String

type Out = String

data Compiler = Ghc | Ghcjs | Guile | Nix
  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)

analyze :: String -> IO Target
analyze s = do
  user <- Env.getEnv "USER"
  root <- Env.getEnv "BIZ_ROOT"
  cwd <- Dir.getCurrentDirectory
  let path = cwd </> s
  case File.takeExtension path of
    ".hs" -> do
      content <- String.lines </ Prelude.readFile path
      let out = content /> Regex.match metaOut |> catMaybes |> head |> require "out"
      let compiler = if ".js" `List.isSuffixOf` out then Ghcjs else Ghc
      return
        Target
          { namespace =
              require "namespace"
                <| path
                |> reps root ""
                |> File.dropExtension
                |> reps "/" "."
                |> List.stripPrefix "."
                >>= Regex.match metaNamespace,
            deps = content /> Regex.match metaDep |> catMaybes,
            builder = user <> "@localhost",
            ..
          }
    ".nix" ->
      return
        Target
          { namespace = reps root "" path |> List.stripPrefix "/" |> require "namespace",
            path = path,
            deps = [],
            compiler = Nix,
            out = "",
            builder =
              join
                [ "ssh://",
                  user,
                  "@dev.simatime.com?ssh-key=/home/",
                  user,
                  "/.ssh/id_rsa"
                ]
          }
    ".scm" ->
      return
        Target
          { namespace = reps root "" path |> List.stripPrefix "/" |> require "namespace",
            path = path,
            deps = [],
            compiler = Guile,
            out = "",
            builder = user <> "@localhost"
          }
    e -> panic <| "bild does not know this extension: " <> Text.pack e

build :: Target -> IO ()
build target@Target {..} = do
  root <- Env.getEnv "BIZ_ROOT"
  case compiler of
    Ghc -> do
      putText <| "bild: dev: ghc: " <> Text.pack namespace
      let outDir = root </> "_/bild/dev/bin"
      Dir.createDirectoryIfMissing True outDir
      putText <| "bild: dev: local: " <> Text.pack builder
      Process.callProcess
        "ghc"
        [ "-Werror",
          "-i" <> root,
          "-odir",
          root </> "_/bild/int",
          "-hidir",
          root </> "_/bild/int",
          "--make",
          path,
          "-main-is",
          namespace,
          "-o",
          outDir </> out
        ]
    Ghcjs -> do
      putText <| "bild: dev: ghcjs: " <> Text.pack namespace
      let outDir = root </> "_/bild/dev/static"
      Dir.createDirectoryIfMissing True outDir
      putText <| "bild: dev: local: " <> Text.pack builder
      Process.callProcess
        "ghcjs"
        [ "-Werror",
          "-i" <> root,
          "-odir",
          root </> "_/bild/int",
          "-hidir",
          root </> "_/bild/int",
          "--make",
          path,
          "-main-is",
          namespace,
          "-o",
          outDir </> out
        ]
    Guile -> do
      putText <| "bild: dev: guile: " <> Text.pack namespace
      let outDir = root </> "_/bild/dev/bin"
      Dir.createDirectoryIfMissing True outDir
      putText <| "bild: dev: local: " <> Text.pack builder
      putText "bild: guile TODO"
      putText <| show target
    Nix -> do
      putText <| "bild: nix: " <> Text.pack namespace
      cwd <- Dir.getCurrentDirectory
      let outDir = root </> "_/bild/nix"
      Dir.createDirectoryIfMissing True outDir
      putText <| "bild: nix: remote: " <> Text.pack builder
      Process.callProcess
        "nix-build"
        [ path,
          "-o",
          outDir </> 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",
          -- Specify remote builders
          "--builders",
          builder
        ]

metaNamespace :: Regex.RE Char Namespace
metaNamespace = name <> Regex.many (Regex.sym '.') <> name
  where
    name = Regex.many (Regex.psym Char.isUpper) <> Regex.many (Regex.psym Char.isLower)

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 (/= ' '))

require :: Text -> Maybe a -> a
require _ (Just x) = x
require s Nothing = panic <| s <> " not found"

-- | Replace 'a' in 's' with 'b'.
reps :: String -> String -> String -> String
reps a b s@(x : xs) =
  if isPrefixOf a s
    then -- then, write 'b' and replace jumping 'a' substring
      b ++ reps a b (drop (length a) s)
    else -- then, write 'x' char and try to replace tail string
      x : reps a b xs
reps _ _ [] = []