#!/usr/bin/env bash

# Relevant environment variables:
#
#    GHC                  (required) compiler to build with
#    CI_CONFIG                       configuration file
#    EXTRA_OPTS                      extra options passed to test-patches
#    USE_NIX                         if 1, use nix to provide build dependencies
#    ONLY_PACKAGES                   restrict set of packages to build
#

set -e

cd ci

if [ -z "$GHC" ]; then
  echo "The \$GHC variable is un-set. Defaulting to 'ghc'."
  GHC="ghc"
fi

if [ -z "$CI_CONFIG" ]; then
  CI_CONFIG=config.sh
fi

EXTRA_OPTS="$@"

if [ -f "$CI_CONFIG" ]; then
  source $CI_CONFIG
else
  echo "Couldn't find CI configuration"
fi

EXTRA_OPTS="$EXTRA_OPTS --cabal-option=-j$CPUS" # Use cabal's build parallelism

mkdir -p run

echo "" > run/deps.cabal.project
if [ -n "$USE_NIX" ]; then
  # Generate native library dependency mapping
  nix eval --raw -f ./. cabalDepsSrc >> run/deps.cabal.project
  run="head-hackage-ci"
else
  run="head-hackage-ci"

  # Sigh, this is an abysmal hack
  bindir=$(realpath .)/run/bin
  mkdir -p $bindir
  PATH=$bindir:$PATH
  cp build-repo.sh $bindir/build-repo.sh
  if ! which tool; then
    echo "Installing hackage-overlay-repo-tool..."
    cabal new-install tool --installdir=$bindir
  fi
  if ! which hackage-repo-tool; then
    echo "Installing hackage-repo-tool..."
    cabal new-install hackage-repo-tool --installdir=$bindir
  fi
  cabal new-install head-hackage-ci --installdir=$bindir
fi

ONLY_PACKAGES=( $ONLY_PACKAGES )

## Setup for capturing eventlogs while running GHC

# Always create the eventlogs directory, so the tar invocation doesn't have to
# be tricky in .gitlab-ci.yml
export EVENTLOG_DIR="$(pwd)/run/eventlogs"
mkdir -p $EVENTLOG_DIR

if [[ -v EVENTLOGGING ]]; then
    LOGGING_GHC="$(pwd)/logging-ghc"
    LOGGING_OPTION="--logging-wrapper=$LOGGING_GHC"
else
    LOGGING_OPTION=""
fi

cd run
rm -f cabal.project
set -x
$run \
  test-patches \
  --extra-cabal-fragment=$(pwd)/deps.cabal.project \
  --patches=../../patches \
  --with-compiler=$GHC \
  $LOGGING_OPTION \
  $EXTRA_OPTS \
  ${ONLY_PACKAGES[@]/#/-o} \
  --ghc-option="$EXTRA_HC_OPTS"
