#!/usr/bin/env cabal
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ViewPatterns #-}

import Data.Aeson as A
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Set as S
import System.Environment
import Data.List

{-
Note [Generating the CI pipeline]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This script is responsible for generating the majority of jobs in the CI pipeline.
In particular, it generates all the standard build configurations which perform a
full build and test of the compiler.

There are broadly three categories of job:

* validate - jobs run on every MR, these are typically validate builds.
* nightly - jobs run once per day on the master branch
* release - jobs for producing release artifacts, these are perf builds.

Basically, for each suitable combination of architecture and operating system these three
jobs are generated which run either.

In reality things are a bit more complicated because

* validate - we run some additional validation jobs which have no corresponding release artifacts
* nightly  - Some builds are only run on nightly, rather than also validate, to
             relieve pressure on CI
* release  - Not all jobs are run in release pipelines, only those which we
             produce release artifacts for.

The job specification can be seen at the bottom of this file in the 'jobs' variable.

The generated jobs assume certain things about the configuration file they are included
into. For example

* The DOCKER_REV variable must be set (which specifies the versions of the docker images)

Things will go very quickly wrong if you don't have the right variables set, the
testing logic in `ci.sh` contains more dependencies on these global variables.

Generating the CI configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In order to regenerate the CI configuration you need to run the ./generate_jobs
script which adds a module header and also formats the output JSON with jq.

Other CI jobs
~~~~~~~~~~~~~

Not all the jobs in the CI pipeline are generated by this script. There are quite a
few ad-hoc jobs (which don't fit into the build/test with hadrian) model. For example

* linters
* hadrian/ghci
* One test which builds with the make build system (until we remove it #17527)

All these definitions are found in the .gitlab-ci.yaml file directly.


Note [Consumers of artifacts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The generated names for the jobs is important as there are a few downstream consumers
of the jobs artifacts. Therefore some care should be taken if changing the generated
names of jobs to update these other places.

1. Fedora33 jobs are required by head.hackage
2. The fetch-gitlab release utility pulls release artifacts from the
3. The ghc-head-from script downloads release artifacts based on a pipeline change.
4. Some subsequent CI jobs have explicit dependencies (for example docs-tarball, perf, perf-nofib)

Note [Generation Modes]
~~~~~~~~~~~~~~~~~~~~~~~

There are two different modes this  script can operate in:

* `gitlab`: Generates a job.yaml which defines all the pipelines for the platforms
* `metadata`: Generates a file which maps a platform the the "default" validate and
              nightly pipeline. This file is intended to be used when generating
              ghcup metadata.

-}

-----------------------------------------------------------------------------
-- Definition of a BuildConfig (options which affect the binaries which are in the bindist)
-----------------------------------------------------------------------------

-- | Operating system
data Opsys
  = Linux LinuxDistro
  | Darwin
  | FreeBSD13
  | Windows deriving (Eq)

data LinuxDistro
  = Debian12
  | Debian11
  | Debian10
  | Debian9
  | Fedora33
  | Fedora38
  | Ubuntu2004
  | Ubuntu1804
  | Alpine312
  | Alpine318
  | AlpineWasm
  | Rocky8
  deriving (Eq)

data Arch = Amd64 | AArch64 | I386

data BignumBackend = Native | Gmp deriving Eq

bignumString :: BignumBackend -> String
bignumString Gmp = "gmp"
bignumString Native = "native"

data CrossEmulator
  = NoEmulator
  | NoEmulatorNeeded
  | Emulator String

-- | A BuildConfig records all the options which can be modified to affect the
-- bindists produced by the compiler.
data BuildConfig
  = BuildConfig { withDwarf      :: Bool
                , unregisterised :: Bool
                , buildFlavour   :: BaseFlavour
                , bignumBackend  :: BignumBackend
                , llvmBootstrap  :: Bool
                , withAssertions :: Bool
                , withNuma       :: Bool
                , withZstd       :: Bool
                , crossTarget    :: Maybe String
                , crossEmulator  :: CrossEmulator
                , configureWrapper :: Maybe String
                , fullyStatic    :: Bool
                , tablesNextToCode :: Bool
                , threadSanitiser :: Bool
                , noSplitSections :: Bool
                , validateNonmovingGc :: Bool
                }

-- Extra arguments to pass to ./configure due to the BuildConfig
configureArgsStr :: BuildConfig -> String
configureArgsStr bc = unwords $
     ["--enable-unregisterised"| unregisterised bc ]
  ++ ["--disable-tables-next-to-code" | not (tablesNextToCode bc) ]
  ++ ["--with-intree-gmp" | Just _ <- pure (crossTarget bc) ]
  ++ ["--with-system-libffi" | crossTarget bc == Just "wasm32-wasi" ]
  ++ ["--enable-ipe-data-compression" | withZstd bc ]
  ++ ["--enable-strict-ghc-toolchain-check"]

-- Compute the hadrian flavour from the BuildConfig
mkJobFlavour :: BuildConfig -> Flavour
mkJobFlavour BuildConfig{..} = Flavour buildFlavour opts
  where
    opts = [Llvm | llvmBootstrap] ++
           [Dwarf | withDwarf] ++
           [FullyStatic | fullyStatic] ++
           [ThreadSanitiser | threadSanitiser] ++
           [NoSplitSections | noSplitSections, buildFlavour == Release ] ++
           [BootNonmovingGc | validateNonmovingGc ]

data Flavour = Flavour BaseFlavour [FlavourTrans]

data FlavourTrans =
      Llvm
    | Dwarf
    | FullyStatic
    | ThreadSanitiser
    | NoSplitSections
    | BootNonmovingGc

data BaseFlavour = Release | Validate | SlowValidate deriving Eq

-----------------------------------------------------------------------------
-- Build Configs
-----------------------------------------------------------------------------

-- | A standard build config
vanilla :: BuildConfig
vanilla = BuildConfig
  { withDwarf      = False
  , unregisterised = False
  , buildFlavour   = Validate
  , bignumBackend  = Gmp
  , llvmBootstrap  = False
  , withAssertions = False
  , withNuma = False
  , withZstd = False
  , crossTarget = Nothing
  , crossEmulator = NoEmulator
  , configureWrapper = Nothing
  , fullyStatic = False
  , tablesNextToCode = True
  , threadSanitiser = False
  , noSplitSections = False
  , validateNonmovingGc = False
  }

splitSectionsBroken :: BuildConfig -> BuildConfig
splitSectionsBroken bc = bc { noSplitSections = True }

nativeInt :: BuildConfig
nativeInt = vanilla { bignumBackend = Native }

dwarf :: BuildConfig
dwarf = vanilla { withDwarf = True }

unreg :: BuildConfig
unreg = vanilla { unregisterised = True }

releaseConfig :: BuildConfig
releaseConfig = vanilla { buildFlavour = Release }

debug :: BuildConfig
debug = vanilla { buildFlavour = SlowValidate
                , withAssertions = True
                -- WithNuma so at least one job tests Numa
                , withNuma = True
                }

zstdIpe :: BuildConfig
zstdIpe = vanilla { withZstd = True }

static :: BuildConfig
static = vanilla { fullyStatic = True }

staticNativeInt :: BuildConfig
staticNativeInt = static { bignumBackend = Native }

crossConfig :: String       -- ^ target triple
            -> CrossEmulator -- ^ emulator for testing
            -> Maybe String -- ^ Configure wrapper
            -> BuildConfig
crossConfig triple emulator configure_wrapper =
    vanilla { crossTarget = Just triple
            , crossEmulator = emulator
            , configureWrapper = configure_wrapper
            }

llvm :: BuildConfig
llvm = vanilla { llvmBootstrap = True }

tsan :: BuildConfig
tsan = vanilla { threadSanitiser = True }

noTntc :: BuildConfig
noTntc = vanilla { tablesNextToCode = False }

-----------------------------------------------------------------------------
-- Platform specific variables
-----------------------------------------------------------------------------

-- | These tags have to match what we call the runners on gitlab
runnerTag :: Arch -> Opsys -> String
runnerTag arch (Linux _) =
  case arch of
    Amd64   -> "x86_64-linux"
    AArch64 -> "aarch64-linux"
    I386    -> "x86_64-linux"
runnerTag AArch64 Darwin = "aarch64-darwin"
runnerTag Amd64 Darwin = "x86_64-darwin-m1"
runnerTag Amd64 Windows = "new-x86_64-windows"
runnerTag Amd64 FreeBSD13 = "x86_64-freebsd13"
runnerTag _ _ = error "Invalid arch/opsys"

tags :: Arch -> Opsys -> BuildConfig -> [String]
tags arch opsys _bc = [runnerTag arch opsys] -- Tag for which runners we can use

-- These names are used to find the docker image so they have to match what is
-- in the docker registry.
distroName :: LinuxDistro -> String
distroName Debian12  = "deb12"
distroName Debian11  = "deb11"
distroName Debian10   = "deb10"
distroName Debian9   = "deb9"
distroName Fedora33  = "fedora33"
distroName Fedora38  = "fedora38"
distroName Ubuntu1804 = "ubuntu18_04"
distroName Ubuntu2004 = "ubuntu20_04"
distroName Alpine312  = "alpine3_12"
distroName Alpine318  = "alpine3_18"
distroName AlpineWasm = "alpine3_18-wasm"
distroName Rocky8     = "rocky8"

opsysName :: Opsys -> String
opsysName (Linux distro) = "linux-" ++ distroName distro
opsysName Darwin = "darwin"
opsysName FreeBSD13 = "freebsd13"
opsysName Windows = "windows"

archName :: Arch -> String
archName Amd64 = "x86_64"
archName AArch64 = "aarch64"
archName I386  = "i386"

binDistName :: Arch -> Opsys -> BuildConfig -> String
binDistName arch opsys bc = "ghc-" ++ testEnv arch opsys bc

-- | Test env should create a string which changes whenever the 'BuildConfig' changes.
-- Either the change is reflected by modifying the flavourString or directly (as is
-- the case for settings which affect environment variables)
testEnv :: Arch -> Opsys -> BuildConfig -> String
testEnv arch opsys bc = intercalate "-" $
                        [ archName arch
                        , opsysName opsys ]
                        ++ ["int_" ++ bignumString (bignumBackend bc) | bignumBackend bc /= Gmp]
                        ++ ["unreg" | unregisterised bc ]
                        ++ ["numa"  | withNuma bc ]
                        ++ ["zstd"  | withZstd bc ]
                        ++ ["no_tntc"  | not (tablesNextToCode bc) ]
                        ++ ["cross_"++triple  | Just triple <- pure $ crossTarget bc ]
                        ++ [flavourString (mkJobFlavour bc)]

-- | The hadrian flavour string we are going to use for this build
flavourString :: Flavour -> String
flavourString (Flavour base trans) = base_string base ++ concatMap (("+" ++) . flavour_string) trans
  where
    base_string Release = "release"
    base_string Validate = "validate"
    base_string SlowValidate = "slow-validate"

    flavour_string Llvm = "llvm"
    flavour_string Dwarf = "debug_info"
    flavour_string FullyStatic = "fully_static"
    flavour_string ThreadSanitiser = "thread_sanitizer_cmm"
    flavour_string NoSplitSections = "no_split_sections"
    flavour_string BootNonmovingGc = "boot_nonmoving_gc"

-- The path to the docker image (just for linux builders)
dockerImage :: Arch -> Opsys -> Maybe String
dockerImage arch (Linux distro) =
    Just image
  where
    image = mconcat
      [ "registry.gitlab.haskell.org/ghc/ci-images/"
      , archName arch
      , "-linux-"
      , distroName distro
      , ":$DOCKER_REV"
      ]
dockerImage _ _ = Nothing

-----------------------------------------------------------------------------
-- Platform specific variables
-----------------------------------------------------------------------------

-- The variables map is a monoidal map so that we don't ever accidentally lose
-- variables settings by silently overwriting when merging. At the end these variables
-- are combinated together with spaces if they are set multiple times. This may
-- produce nonsense but it's easier to debug that silently overwriting.
--
-- The "proper" solution would be to use a dependent monoidal map where each key specifies
-- the combination behaviour of it's values. Ie, whether setting it multiple times is an error
-- or they should be combined.
newtype MonoidalMap k v = MonoidalMap { unMonoidalMap :: Map k v }
    deriving (Eq, Show, Functor, ToJSON)

instance (Ord k, Semigroup v) => Semigroup (MonoidalMap k v) where
    (MonoidalMap a) <> (MonoidalMap b) = MonoidalMap (Map.unionWith (<>) a b)

instance (Ord k, Semigroup v) => Monoid (MonoidalMap k v) where
    mempty = MonoidalMap Map.empty

mminsertWith :: Ord k => (a -> a -> a) -> k -> a -> MonoidalMap k a -> MonoidalMap k a
mminsertWith f k v (MonoidalMap m) = MonoidalMap (Map.insertWith f k v m)

mmlookup :: Ord k => k -> MonoidalMap k a -> Maybe a
mmlookup k (MonoidalMap m) = Map.lookup k m

type Variables = MonoidalMap String [String]

(=:) :: String -> String -> Variables
a =: b = MonoidalMap (Map.singleton a [b])

opsysVariables :: Arch -> Opsys -> Variables
opsysVariables _ FreeBSD13 = mconcat
  [ -- N.B. we use iconv from ports as I see linker errors when we attempt
    -- to use the "native" iconv embedded in libc as suggested by the
    -- porting guide [1].
    -- [1] https://www.freebsd.org/doc/en/books/porters-handbook/using-iconv.html)
    "CONFIGURE_ARGS" =:  "--with-gmp-includes=/usr/local/include --with-gmp-libraries=/usr/local/lib --with-iconv-includes=/usr/local/include --with-iconv-libraries=/usr/local/lib"
  , "HADRIAN_ARGS" =: "--docs=no-sphinx"
  , "GHC_VERSION" =: "9.6.4"
  , "CABAL_INSTALL_VERSION" =: "3.10.2.0"
  ]
opsysVariables _ (Linux distro) = distroVariables distro
opsysVariables AArch64 (Darwin {}) =
  mconcat [ "NIX_SYSTEM" =: "aarch64-darwin"
          , "MACOSX_DEPLOYMENT_TARGET" =: "11.0"
          , "LANG" =: "en_US.UTF-8"
          , "CONFIGURE_ARGS" =: "--with-intree-gmp --with-system-libffi"
          -- Fonts can't be installed on darwin
          , "HADRIAN_ARGS" =: "--docs=no-sphinx-pdfs"
          ]
opsysVariables Amd64 (Darwin {}) =
  mconcat [ "NIX_SYSTEM" =: "x86_64-darwin"
          , "MACOSX_DEPLOYMENT_TARGET" =: "10.13"
          -- "# Only Sierra and onwards supports clock_gettime. See #12858"
          , "ac_cv_func_clock_gettime" =: "no"
          -- # Only newer OS Xs support utimensat. See #17895
          , "ac_cv_func_utimensat" =: "no"
          -- # Only newer OS Xs support futimens. See #22938
          , "ac_cv_func_futimens" =: "no"
          , "LANG" =: "en_US.UTF-8"
          , "CONFIGURE_ARGS" =: "--with-intree-gmp --with-system-libffi"
          -- Fonts can't be installed on darwin
          , "HADRIAN_ARGS" =: "--docs=no-sphinx-pdfs"

          ]
opsysVariables _ (Windows {}) =
  mconcat [ "MSYSTEM" =: "CLANG64"
          , "LANG" =: "en_US.UTF-8"
          , "CABAL_INSTALL_VERSION" =: "3.10.2.0"
          , "HADRIAN_ARGS" =: "--docs=no-sphinx-pdfs"
          , "GHC_VERSION" =: "9.6.4" ]
opsysVariables _ _ = mempty

alpineVariables = mconcat
  [ -- Due to #20266
    "CONFIGURE_ARGS" =: "--disable-ld-override"
  , "INSTALL_CONFIGURE_ARGS" =: "--disable-ld-override"
    -- encoding004: due to lack of locale support
    -- T10458, ghcilink002: due to #17869
  , "BROKEN_TESTS" =: "encoding004 T10458"
  ]


distroVariables :: LinuxDistro -> Variables
distroVariables Alpine312 = alpineVariables
distroVariables Alpine318 = alpineVariables
distroVariables Fedora33 = mconcat
  -- LLC/OPT do not work for some reason in our fedora images
  -- These tests fail with this error: T11649 T5681 T7571 T8131b
  -- +/opt/llvm/bin/opt: /lib64/libtinfo.so.5: no version information available (required by /opt/llvm/bin/opt)
-- +/opt/llvm/bin/llc: /lib64/libtinfo.so.5: no version information available (required by /opt/llvm/bin/llc)
  [ "LLC" =: "/bin/false"
  , "OPT" =: "/bin/false"
  ]
distroVariables _ = mempty

-----------------------------------------------------------------------------
-- Cache settings, what to cache and when can we share the cache
-----------------------------------------------------------------------------

data Cache
  = Cache { cacheKey :: String
          , cachePaths :: [String]
          }

-- The cache doesn't depend on the BuildConfig because we only cache the cabal store.
mkCacheKey :: Arch -> Opsys -> String
mkCacheKey arch opsys = archName arch <> "-" <> opsysName opsys <> "-$CACHE_REV"

instance ToJSON Cache where
  toJSON Cache {..} = object
    [ "key" A..= cacheKey
    , "paths" A..= cachePaths
    ]

-----------------------------------------------------------------------------
-- Artifacts, what to store and how long for
-----------------------------------------------------------------------------

data Artifacts
  = Artifacts { artifactPaths :: [String]
              , junitReport   :: String
              , expireIn      :: String
              , artifactsWhen :: ArtifactsWhen
              }

instance ToJSON Artifacts where
  toJSON Artifacts{..} = object
    [ "reports" A..= object
      [ "junit" A..= junitReport
      ]
    , "expire_in" A..= expireIn
    , "paths" A..= artifactPaths
    , "when" A..= artifactsWhen
    ]

data ArtifactsWhen = ArtifactsOnSuccess | ArtifactsOnFailure | ArtifactsAlways

instance ToJSON ArtifactsWhen where
  toJSON ArtifactsOnSuccess = "on_success"
  toJSON ArtifactsOnFailure = "on_failure"
  toJSON ArtifactsAlways = "always"

-----------------------------------------------------------------------------
-- Rules, when do we run a job
-----------------------------------------------------------------------------

-- Data structure which records the condition when a job is run.
data OnOffRules = OnOffRules { rule_set :: Rule -- ^ The enabled rules
                             , when :: ManualFlag   -- ^ The additional condition about when to run this job.
                             }

-- The initial set of rules, which assumes a Validate pipeline which is run with FullCI.
emptyRules :: OnOffRules
emptyRules = OnOffRules (ValidateOnly (S.singleton FullCI)) OnSuccess

-- When to run the job
data ManualFlag = Manual -- ^ Only run the job when explicitly triggered by a user
                | OnSuccess -- ^ Always run it, if the rules pass (the default)
                deriving Eq

setRule :: Rule -> OnOffRules -> OnOffRules
setRule r (OnOffRules _ m) = OnOffRules r m

enableValidateRule :: ValidateRule -> OnOffRules -> OnOffRules
enableValidateRule r = modifyValidateRules (S.insert r)

onlyValidateRule :: ValidateRule -> OnOffRules -> OnOffRules
onlyValidateRule r  = modifyValidateRules (const (S.singleton r))

removeValidateRule :: ValidateRule -> OnOffRules -> OnOffRules
removeValidateRule r = modifyValidateRules (S.delete r)

modifyValidateRules :: (S.Set ValidateRule -> S.Set ValidateRule) -> OnOffRules -> OnOffRules
modifyValidateRules f (OnOffRules (ValidateOnly rs) m) = OnOffRules (ValidateOnly (f rs)) m
modifyValidateRules _ r = error $ "Applying validate rule to nightly/release job:" ++ show (rule_set r)

manualRule :: OnOffRules -> OnOffRules
manualRule rules = rules { when = Manual }

-- Given 'OnOffRules', returns a list of ALL rules with their toggled status.
-- For example, even if you don't explicitly disable a rule it will end up in the
-- rule list with the OFF state.
enumRules :: OnOffRules -> [OnOffRule]
enumRules (OnOffRules r _) = rulesList
  where
    rulesList = case r of
                  ValidateOnly rs -> [OnOffRule On (ValidateOnly rs)
                                    , OnOffRule Off ReleaseOnly
                                    , OnOffRule Off Nightly ]
                  Nightly -> [ OnOffRule Off (ValidateOnly S.empty)
                             , OnOffRule Off ReleaseOnly
                             , OnOffRule On Nightly ]
                  ReleaseOnly -> [ OnOffRule Off (ValidateOnly S.empty)
                                 , OnOffRule On ReleaseOnly
                                 , OnOffRule Off Nightly ]



data OnOffRule = OnOffRule OnOff Rule

data OnOff = On | Off

instance ToJSON ManualFlag where
  toJSON Manual = "manual"
  toJSON OnSuccess = "on_success"

instance ToJSON OnOffRules where
  toJSON rules = toJSON [object ([
    "if" A..= and_all (map one_rule (enumRules rules))
    , "when" A..= toJSON (when rules)]
    -- Necessary to stop manual jobs stopping pipeline progress
    -- https://docs.gitlab.com/ee/ci/yaml/#rulesallow_failure
    ++
    ["allow_failure" A..= True | when rules == Manual ])]

    where
      one_rule (OnOffRule onoff r) = ruleString onoff r


parens :: [Char] -> [Char]
parens s = "(" ++ s ++ ")"
and_all :: [[Char]] -> [Char]
and_all rs = intercalate " && " (map parens rs)
or_all :: [[Char]] -> [Char]
or_all rs = intercalate " || " (map parens rs)

-- | A Rule corresponds to some condition which must be satisifed in order to
-- run the job.
data Rule = ReleaseOnly  -- ^ Only run this job in a release pipeline
          | Nightly      -- ^ Only run this job in the nightly pipeline
          | ValidateOnly (S.Set ValidateRule) -- ^ Only run this job in a validate pipeline, when any of these rules are enabled.
          deriving (Show, Ord, Eq)

data ValidateRule =
            FullCI       -- ^ Run this job when the "full-ci" label is present.
          | LLVMBackend  -- ^ Run this job when the "LLVM backend" label is present
          | JSBackend    -- ^ Run this job when the "javascript" label is present
          | FreeBSDLabel -- ^ Run this job when the "FreeBSD" label is set.
          | NonmovingGc  -- ^ Run this job when the "non-moving GC" label is set.
          | IpeData      -- ^ Run this job when the "IPE" label is set
          | TestPrimops  -- ^ Run this job when "test-primops" label is set
          deriving (Show, Enum, Bounded, Ord, Eq)

-- A constant evaluating to True because gitlab doesn't support "true" in the
-- expression language.
true :: String
true =  "\"true\" == \"true\""
-- A constant evaluating to False because gitlab doesn't support "true" in the
-- expression language.
_false :: String
_false = "\"disabled\" != \"disabled\""

-- Convert the state of the rule into a string that gitlab understand.
ruleString :: OnOff -> Rule -> String
ruleString On (ValidateOnly vs) =
  case S.toList vs of
    [] -> true
    conds -> or_all (map validateRuleString conds)
ruleString Off (ValidateOnly {}) = true
ruleString On ReleaseOnly = "$RELEASE_JOB == \"yes\""
ruleString Off ReleaseOnly = "$RELEASE_JOB != \"yes\""
ruleString On Nightly = "$NIGHTLY"
ruleString Off Nightly = "$NIGHTLY == null"

labelString :: String -> String
labelString s =  "$CI_MERGE_REQUEST_LABELS =~ /.*" ++ s ++ ".*/"

branchStringExact :: String -> String
branchStringExact s = "$CI_COMMIT_BRANCH == \"" ++ s ++ "\""

branchStringLike :: String -> String
branchStringLike s = "$CI_COMMIT_BRANCH =~ /" ++ s ++ "/"


validateRuleString :: ValidateRule -> String
validateRuleString FullCI = or_all ([ labelString "full-ci"
                                    , labelString "marge_bot_batch_merge_job"
                                    , branchStringExact "master"
                                    , branchStringLike "ghc-[0-9]+\\.[0-9]+"
                                    ])

validateRuleString LLVMBackend  = labelString "LLVM backend"
validateRuleString JSBackend    = labelString "javascript"
validateRuleString FreeBSDLabel = labelString "FreeBSD"
validateRuleString NonmovingGc  = labelString "non-moving GC"
validateRuleString IpeData      = labelString "IPE"
validateRuleString TestPrimops  = labelString "test-primops"

-- | A 'Job' is the description of a single job in a gitlab pipeline. The
-- job contains all the information about how to do the build but can be further
-- modified with information about when to run jobs, which variables to set for
-- certain platforms and so on.
data Job
  = Job { jobStage :: String
        , jobNeeds :: [String]
        , jobTags :: [String]
        , jobAllowFailure :: Bool
        , jobScript :: [String]
        , jobAfterScript :: [String]
        , jobDockerImage :: Maybe String
        , jobVariables :: Variables
        , jobDependencies :: [String]
        , jobArtifacts :: Artifacts
        , jobCache :: Cache
        , jobRules :: OnOffRules
        , jobPlatform  :: (Arch, Opsys)
        }

instance ToJSON Job where
  toJSON Job{..} = object
    [ "stage" A..= jobStage
    -- Convoluted to avoid download artifacts from ghci job
    -- https://docs.gitlab.com/ee/ci/yaml/#needsartifacts
    , "needs" A..= map (\j -> object [ "job" A..= j, "artifacts" A..= False ]) jobNeeds
    , "dependencies" A..= jobDependencies
    , "image" A..= jobDockerImage
    , "tags" A..= jobTags
    , "allow_failure" A..= jobAllowFailure
    -- Joining up variables like this may well be the wrong thing to do but
    -- at least it doesn't lose information silently by overriding.
    , "variables" A..= fmap unwords jobVariables
    , "artifacts" A..= jobArtifacts
    , "cache" A..= jobCache
    , "after_script" A..= jobAfterScript
    , "script" A..= jobScript
    , "rules" A..= jobRules
    ]

-- | Build a job description from the system description and 'BuildConfig'
job :: Arch -> Opsys -> BuildConfig -> NamedJob Job
job arch opsys buildConfig = NamedJob { name = jobName, jobInfo = Job {..} }
  where
    jobPlatform = (arch, opsys)

    jobRules = emptyRules

    jobName = testEnv arch opsys buildConfig

    jobTags = tags arch opsys buildConfig

    jobDockerImage = dockerImage arch opsys

    jobScript
      | Windows <- opsys
      = [ "bash .gitlab/ci.sh setup"
        , "bash .gitlab/ci.sh configure"
        , "bash .gitlab/ci.sh build_hadrian"
        , "bash .gitlab/ci.sh test_hadrian" ]
      | otherwise
      = [ "find libraries -name config.sub -exec cp config.sub {} \\;" | Darwin == opsys ] ++
        [ "sudo chown ghc:ghc -R ." | Linux {} <- [opsys]] ++
        [ ".gitlab/ci.sh setup"
        , ".gitlab/ci.sh configure"
        , ".gitlab/ci.sh build_hadrian"
        , ".gitlab/ci.sh test_hadrian"
        ]

    jobAfterScript
      | Windows <- opsys =
      [ "bash .gitlab/ci.sh save_cache"
      , "bash .gitlab/ci.sh save_test_output"
      , "bash .gitlab/ci.sh clean"
      ]
      | otherwise =
      [ ".gitlab/ci.sh save_cache"
      , ".gitlab/ci.sh save_test_output"
      , ".gitlab/ci.sh clean"
      , "cat ci_timings" ]

    jobFlavour = mkJobFlavour buildConfig

    jobDependencies = []
    jobVariables = mconcat
      [ opsysVariables arch opsys
      , "TEST_ENV" =: testEnv arch opsys buildConfig
      , "BIN_DIST_NAME" =: binDistName arch opsys buildConfig
      , "BUILD_FLAVOUR" =: flavourString jobFlavour
      , "BIGNUM_BACKEND" =: bignumString (bignumBackend buildConfig)
      , "CONFIGURE_ARGS" =: configureArgsStr buildConfig
      , maybe mempty ("CONFIGURE_WRAPPER" =:) (configureWrapper buildConfig)
      , maybe mempty ("CROSS_TARGET" =:) (crossTarget buildConfig)
      , case crossEmulator buildConfig of
          NoEmulator       -> case crossTarget buildConfig of
            Nothing -> mempty
            Just _  -> "CROSS_EMULATOR" =: "NOT_SET" -- we need an emulator but it isn't set. Won't run the testsuite
          Emulator s       -> "CROSS_EMULATOR" =: s
          NoEmulatorNeeded -> mempty
      , if withNuma buildConfig then "ENABLE_NUMA" =: "1" else mempty
      , let runtestArgs =
                [ "--way=nonmoving --way=nonmoving_thr --way=nonmoving_thr_sanity"
                | validateNonmovingGc buildConfig
                ]
        in "RUNTEST_ARGS" =: unwords runtestArgs
      ]

    jobArtifacts = Artifacts
      { junitReport = "junit.xml"
      , expireIn = "2 weeks"
      , artifactPaths = [binDistName arch opsys buildConfig ++ ".tar.xz"
                        ,"junit.xml"
                        ,"unexpected-test-output.tar.gz"]
      , artifactsWhen = ArtifactsAlways
      }

    jobCache
        -- N.B. We have temporarily disabled cabal-install store caching on
        -- Windows due to #21347.
      | Windows <- opsys =
          Cache { cachePaths = [], cacheKey = "no-caching" }
      | otherwise = Cache
          { cachePaths = [ "cabal-cache", "toolchain" ]
          , cacheKey = mkCacheKey arch opsys

          }

    jobAllowFailure = False
    jobStage = "full-build"
    jobNeeds = ["hadrian-ghc-in-ghci"]

---------------------------------------------------------------------------
-- Job Modifiers
---------------------------------------------------------------------------

-- Generic modification functions

-- | Modify all jobs in a 'JobGroup'
modifyJobs :: (a -> a) -> JobGroup a -> JobGroup a
modifyJobs = fmap

-- | Modify just the validate jobs in a 'JobGroup'
modifyValidateJobs :: (a -> a) -> JobGroup a -> JobGroup a
modifyValidateJobs f jg = jg { v = fmap f <$> v jg }

-- | Modify just the nightly jobs in a 'JobGroup'
modifyNightlyJobs :: (a -> a) -> JobGroup a -> JobGroup a
modifyNightlyJobs f jg = jg { n = fmap f <$> n jg }

-- Generic helpers

setJobRule :: Rule -> Job -> Job
setJobRule r j = j { jobRules = setRule r (jobRules j) }

addValidateJobRule :: ValidateRule -> Job -> Job
addValidateJobRule r = modifyValidateJobRule (enableValidateRule r)

onlyValidateJobRule :: ValidateRule -> Job -> Job
onlyValidateJobRule r = modifyValidateJobRule (onlyValidateRule r)

removeValidateJobRule :: ValidateRule -> Job -> Job
removeValidateJobRule r = modifyValidateJobRule (removeValidateRule r)

modifyValidateJobRule :: (OnOffRules -> OnOffRules) -> Job -> Job
modifyValidateJobRule f j = j { jobRules = f (jobRules j) }

addVariable :: String -> String -> Job -> Job
addVariable k v j = j { jobVariables = mminsertWith (++) k [v] (jobVariables j) }

setVariable :: String -> String -> Job -> Job
setVariable k v j = j { jobVariables = MonoidalMap $ Map.insert k [v] $ unMonoidalMap $ jobVariables j }

delVariable :: String -> Job -> Job
delVariable k j = j { jobVariables = MonoidalMap $ Map.delete k $ unMonoidalMap $ jobVariables j }

-- Building the standard jobs
--
-- | Make a normal validate CI job
validate :: Arch -> Opsys -> BuildConfig -> NamedJob Job
validate = job

-- Nightly and release apply the FastCI configuration to all jobs so that they all run in
-- the pipeline (not conditional on the full-ci label)
nightlyRule :: Job -> Job
nightlyRule = setJobRule Nightly

releaseRule :: Job -> Job
releaseRule = setJobRule ReleaseOnly

-- | Make a normal nightly CI job
nightly :: Arch -> Opsys -> BuildConfig -> NamedJob Job
nightly arch opsys bc =
  let NamedJob n j = job arch opsys bc
  in NamedJob { name = "nightly-" ++ n, jobInfo = nightlyRule . keepArtifacts "8 weeks" . highCompression $ j}

-- | Make a normal release CI job
release :: Arch -> Opsys -> BuildConfig -> NamedJob Job
release arch opsys bc =
  let NamedJob n j = job arch opsys (bc { buildFlavour = Release })
  in NamedJob { name = "release-" ++ n, jobInfo = releaseRule . keepArtifacts "1 year" . ignorePerfFailures . useHashUnitIds . highCompression $ j}

-- Specific job modification functions

-- | Mark a job as requiring a manual trigger.
manual :: Job -> Job
manual j = j { jobRules = manualRule (jobRules j) }

-- | Mark a job as allowed to fail
allowFailure :: Job -> Job
allowFailure j = j { jobAllowFailure = True }

-- | Modify the time the job keeps its artifacts for
keepArtifacts :: String -> Job -> Job
keepArtifacts l j = j { jobArtifacts = (jobArtifacts j) { expireIn = l } }

-- | Ignore performance test failures for this job
ignorePerfFailures :: Job -> Job
ignorePerfFailures = addVariable "IGNORE_PERF_FAILURES" "all"

-- | Use a higher compression level to produce the job bindists (slower but produces
-- smaller results)
highCompression :: Job -> Job
highCompression = addVariable "XZ_OPT" "-9"

useHashUnitIds :: Job -> Job
useHashUnitIds = addVariable "HADRIAN_ARGS" "--hash-unit-ids"

-- | Mark the validate job to run in fast-ci mode
-- This is default way, to enable all jobs you have to apply the `full-ci` label.
fastCI :: JobGroup Job -> JobGroup Job
fastCI = modifyValidateJobs (removeValidateJobRule FullCI)

-- | Mark a group of jobs as allowed to fail.
allowFailureGroup :: JobGroup Job -> JobGroup Job
allowFailureGroup = modifyJobs allowFailure

-- | Add a 'Rule' to just the validate job, for example, only run a job if a certain
-- label is set.
addValidateRule :: ValidateRule -> JobGroup Job -> JobGroup Job
addValidateRule t = modifyValidateJobs (addValidateJobRule t)

-- | Only run a validate job if a certain rule is enabled
onlyRule :: ValidateRule -> JobGroup Job -> JobGroup Job
onlyRule t = modifyValidateJobs (onlyValidateJobRule t)

-- | Don't run the validate job, normally used to alleviate CI load by marking
-- jobs which are unlikely to fail (ie different linux distros)
disableValidate :: JobGroup Job -> JobGroup Job
disableValidate st = st { v = Nothing }

data NamedJob a = NamedJob { name :: String, jobInfo :: a } deriving (Show, Functor)

renameJob :: (String -> String) -> NamedJob a -> NamedJob a
renameJob f (NamedJob n i) = NamedJob (f n) i

instance ToJSON a => ToJSON (NamedJob a) where
  toJSON nj = object
    [ "name" A..= name nj
    , "jobInfo" A..= jobInfo nj ]


--data NamedJobGroup a = NamedJobGroup { platform :: String, jg :: JobGroup a }

-- Jobs are grouped into either triples or pairs depending on whether the
-- job is just validate and nightly, or also release.
data JobGroup a = StandardTriple { v :: Maybe (NamedJob a)
                                 , n :: Maybe (NamedJob a)
                                 , r :: Maybe (NamedJob a) } deriving (Functor, Show)

instance ToJSON a => ToJSON (JobGroup a) where
  toJSON StandardTriple{..} = object
    [ "v" A..= v
    , "n" A..= n
    , "r" A..= r
    ]

rename :: (String -> String) -> JobGroup a -> JobGroup a
rename f (StandardTriple nv nn nr) = StandardTriple (renameJob f <$> nv) (renameJob f <$> nn) (renameJob f <$> nr)

-- | Construct a 'JobGroup' which consists of a validate, nightly and release build with
-- a specific config.
standardBuildsWithConfig :: Arch -> Opsys -> BuildConfig -> JobGroup Job
standardBuildsWithConfig a op bc =
  StandardTriple (Just (validate a op bc))
                 (Just (nightly a op bc))
                 (Just (release a op bc))

-- | Construct a 'JobGroup' which consists of a validate, nightly and release builds with
-- the 'vanilla' config.
standardBuilds :: Arch -> Opsys -> JobGroup Job
standardBuilds a op = standardBuildsWithConfig a op vanilla

-- | Construct a 'JobGroup' which just consists of a validate and nightly build. We don't
-- produce releases for these jobs.
validateBuilds :: Arch -> Opsys -> BuildConfig -> JobGroup Job
validateBuilds a op bc = StandardTriple { v = Just (validate a op bc)
                                        , n = Just (nightly a op bc)
                                        , r = Nothing }

flattenJobGroup :: JobGroup a -> [(String, a)]
flattenJobGroup (StandardTriple a b c) = map flattenNamedJob (catMaybes [a,b,c])

flattenNamedJob :: NamedJob a -> (String, a)
flattenNamedJob (NamedJob n i) = (n, i)


-- | Specification for all the jobs we want to build.
jobs :: Map String Job
jobs = Map.fromList $ concatMap (flattenJobGroup) job_groups

job_groups :: [JobGroup Job]
job_groups =
     [ disableValidate (standardBuilds Amd64 (Linux Debian10))
     , addValidateRule TestPrimops (standardBuildsWithConfig Amd64 (Linux Debian10) dwarf)
     , validateBuilds Amd64 (Linux Debian10) nativeInt
     , validateBuilds Amd64 (Linux Debian10) unreg
     , fastCI (validateBuilds Amd64 (Linux Debian10) debug)
     , -- More work is needed to address TSAN failures: #22520
       modifyNightlyJobs allowFailure
         (modifyValidateJobs (allowFailure . manual) tsan_jobs)
     , -- Nightly allowed to fail: #22343
       modifyNightlyJobs allowFailure
        (modifyValidateJobs manual (validateBuilds Amd64 (Linux Debian10) noTntc))
     , onlyRule LLVMBackend (validateBuilds Amd64 (Linux Debian12) llvm)
     , disableValidate (standardBuilds Amd64 (Linux Debian11))
     , disableValidate (standardBuilds Amd64 (Linux Debian12))
     -- We still build Deb9 bindists for now due to Ubuntu 18 and Linux Mint 19
     -- not being at EOL until April 2023 and they still need tinfo5.
     , disableValidate (standardBuildsWithConfig Amd64 (Linux Debian9) (splitSectionsBroken vanilla))
     , disableValidate (standardBuilds Amd64 (Linux Ubuntu1804))
     , disableValidate (standardBuilds Amd64 (Linux Ubuntu2004))
     , disableValidate (standardBuilds Amd64 (Linux Rocky8))
     -- Fedora33 job is always built with perf so there's one job in the normal
     -- validate pipeline which is built with perf.
     , fastCI (standardBuildsWithConfig Amd64 (Linux Fedora33) releaseConfig)
     -- This job is only for generating head.hackage docs
     , hackage_doc_job (disableValidate (standardBuildsWithConfig Amd64 (Linux Fedora33) releaseConfig))
     , disableValidate (standardBuildsWithConfig Amd64 (Linux Fedora33) dwarf)
     , disableValidate (standardBuilds Amd64 (Linux Fedora38))
     , fastCI (standardBuildsWithConfig Amd64 Windows vanilla)
     , disableValidate (standardBuildsWithConfig Amd64 Windows nativeInt)
     , addValidateRule TestPrimops (standardBuilds Amd64 Darwin)
     , allowFailureGroup (onlyRule FreeBSDLabel (validateBuilds Amd64 FreeBSD13 vanilla))
     , fastCI (standardBuilds AArch64 Darwin)
     , fastCI (standardBuildsWithConfig AArch64 (Linux Debian10) (splitSectionsBroken vanilla))
     , disableValidate (standardBuildsWithConfig AArch64 (Linux Debian11) (splitSectionsBroken vanilla))
     , onlyRule LLVMBackend (validateBuilds AArch64 (Linux Debian12) llvm)
     , standardBuildsWithConfig I386 (Linux Debian10) (splitSectionsBroken vanilla)
     -- Fully static build, in theory usable on any linux distribution.
     , fullyStaticBrokenTests (standardBuildsWithConfig Amd64 (Linux Alpine312) (splitSectionsBroken static))
     -- Dynamically linked build, suitable for building your own static executables on alpine
     , disableValidate (allowFailureGroup (standardBuildsWithConfig Amd64 (Linux Alpine312) (splitSectionsBroken vanilla)))
     , disableValidate (standardBuildsWithConfig AArch64 (Linux Alpine318) (splitSectionsBroken vanilla))
     , disableValidate (standardBuildsWithConfig Amd64 (Linux Alpine318) (splitSectionsBroken vanilla))
     , fullyStaticBrokenTests (disableValidate (allowFailureGroup (standardBuildsWithConfig Amd64 (Linux Alpine312) staticNativeInt)))
     , validateBuilds Amd64 (Linux Debian11) (crossConfig "aarch64-linux-gnu" (Emulator "qemu-aarch64 -L /usr/aarch64-linux-gnu") Nothing)

     , addValidateRule JSBackend (validateBuilds Amd64 (Linux Debian11) javascriptConfig)

     , make_wasm_jobs wasm_build_config
     , modifyValidateJobs manual $
         make_wasm_jobs wasm_build_config {bignumBackend = Native}
     , modifyValidateJobs manual $
         make_wasm_jobs wasm_build_config {unregisterised = True}
     , onlyRule NonmovingGc (validateBuilds Amd64 (Linux Debian11) vanilla {validateNonmovingGc = True})
     , onlyRule IpeData (validateBuilds Amd64 (Linux Debian10) zstdIpe)
     ]

  where
    javascriptConfig = (crossConfig "javascript-unknown-ghcjs" (Emulator "js-emulator") (Just "emconfigure"))
                         { bignumBackend = Native }

    -- ghcilink002 broken due to #17869
    --
    -- linker_unload_native: due to musl not supporting any means of probing dynlib dependencies
    -- (see Note [Object unloading]).
    fullyStaticBrokenTests = modifyJobs (addVariable "BROKEN_TESTS" "ghcilink002 linker_unload_native")

    hackage_doc_job = rename (<> "-hackage") . modifyJobs (addVariable "HADRIAN_ARGS" "--haddock-for-hackage")

    tsan_jobs =
      modifyJobs
        ( addVariable "TSAN_OPTIONS" "suppressions=$CI_PROJECT_DIR/rts/.tsan-suppressions"
         -- Haddock is large enough to make TSAN choke without massive quantities of
         -- memory.
        . addVariable "HADRIAN_ARGS" "--docs=none") $
      validateBuilds Amd64 (Linux Debian12) tsan

    make_wasm_jobs cfg =
      modifyJobs
        ( delVariable "BROKEN_TESTS"
            . setVariable "HADRIAN_ARGS" "--docs=none"
            . delVariable "INSTALL_CONFIGURE_ARGS"
        )
        $ validateBuilds Amd64 (Linux AlpineWasm) cfg

    wasm_build_config =
      (crossConfig "wasm32-wasi" NoEmulatorNeeded Nothing)
        {
          fullyStatic = True
          , buildFlavour     = Release -- TODO: This needs to be validate but wasm backend doesn't pass yet
        }


mkPlatform :: Arch -> Opsys -> String
mkPlatform arch opsys = archName arch <> "-" <> opsysName opsys

-- | This map tells us for a specific arch/opsys combo what the job name for
-- nightly/release pipelines is. This is used by the ghcup metadata generation so that
-- things like bindist names etc are kept in-sync.
--
-- For cases where there are just
--
-- Otherwise:
--  * Prefer jobs which have a corresponding release pipeline
--  * Explicitly require tie-breaking for other cases.
platform_mapping :: Map String (JobGroup BindistInfo)
platform_mapping = Map.map go combined_result
  where
    whitelist = [ "x86_64-linux-alpine3_12-validate"
                , "x86_64-linux-deb11-validate"
                , "x86_64-linux-deb12-validate"
                , "x86_64-linux-deb10-validate+debug_info"
                , "x86_64-linux-fedora33-release"
                , "x86_64-linux-deb11-cross_aarch64-linux-gnu-validate"
                , "x86_64-windows-validate"
                , "nightly-x86_64-linux-alpine3_18-wasm-cross_wasm32-wasi-release+fully_static"
                , "nightly-x86_64-linux-deb11-validate"
                , "nightly-x86_64-linux-deb12-validate"
                , "x86_64-linux-alpine3_18-wasm-cross_wasm32-wasi-release+fully_static"
                , "x86_64-linux-deb12-validate+thread_sanitizer_cmm"
                , "nightly-aarch64-linux-deb10-validate"
                , "nightly-x86_64-linux-alpine3_12-validate"
                , "nightly-x86_64-linux-deb10-validate"
                , "nightly-x86_64-linux-fedora33-release"
                , "nightly-x86_64-windows-validate"
                , "release-x86_64-linux-alpine3_12-release+no_split_sections"
                , "release-x86_64-linux-deb10-release"
                , "release-x86_64-linux-deb11-release"
                , "release-x86_64-linux-deb12-release"
                , "release-x86_64-linux-fedora33-release"
                , "release-x86_64-windows-release"
                ]

    process sel = Map.fromListWith combine [ (uncurry mkPlatform (jobPlatform (jobInfo $ j)), j) | (sel -> Just j) <- job_groups  ]

    vs = process v
    ns = process n
    rs = process r

    all_platforms = Map.keysSet vs <> Map.keysSet ns <> Map.keysSet rs

    combined_result = Map.fromList [ (p, StandardTriple { v = Map.lookup p vs
                                                        , n = Map.lookup p ns
                                                        , r = Map.lookup p rs })
                                   | p <- S.toList all_platforms ]

    combine a b
      | name a `elem` whitelist = a -- Explicitly selected
      | name b `elem` whitelist = b
      | otherwise = error (show (name a) ++ show (name b))

    go = fmap (BindistInfo . unwords . fromJust . mmlookup "BIN_DIST_NAME" . jobVariables)


data BindistInfo = BindistInfo { bindistName :: String } deriving Show

instance ToJSON BindistInfo where
  toJSON (BindistInfo n) = object [ "bindistName" A..= n ]


main :: IO ()
main = do
  ass <- getArgs
  case ass of
    -- See Note [Generation Modes]
    ("gitlab":as) -> write_result as jobs
    ("metadata":as) -> write_result as platform_mapping
    _ -> error "gen_ci.hs <gitlab|metadata> [file.json]"

write_result :: ToJSON a => [FilePath] -> a -> IO ()
write_result as obj =
  (case as of
    [] -> B.putStrLn
    (fp:_) -> B.writeFile fp)
    (A.encode obj)
