#!/bin/bash

# Build the Charliecloud source code in $1, install it to prefix $2, and do
# some basic validations.


. "$(dirname "$0")"/base.bash

# Fool Shellcheck into thinking these variables that come from CI are set.
# shellcheck disable=SC2034
if false; then
    ci_gc=
fi

if [[ -n $2 ]]; then
    prefox=$(realpath "$2")  # I like this typo and am rolling with it. 😂
    prefox_arg="--prefix=$prefox"
fi
cd "$1" || exit 1            # satisfy ShellCheck


# Configure.

if [[ $CH_TEST_PACK_FMT = squash-mount ]]; then
    squashfuse=yes
else
    squashfuse=no
fi
gc=${ci_gc#*-}  # remove “gc-” prefix

if [[ ! -f ./configure ]]; then
    ./autogen.sh
fi

./configure "$prefox_arg" --with-squashfuse=$squashfuse --with-gc="$gc"


# Validate configure output.

clrequire 'documentation: yes'

clrequire "garbage collection: $gc"
clrequire 'JSON features: yes'

if [[ $CH_TEST_BUILDER = ch-image ]]; then
    clrequire 'with ch-image(1): yes'
fi

if [[ $CH_TEST_PACK_FMT = squash-mount ]]; then
    clrequire 'recommended tests, squash-mount mode: yes'
    clrequire 'internal SquashFS mounting ... yes'
else
    clrequire 'recommended tests, squash-mount mode: no'
    clrequire 'internal SquashFS mounting ... no'
fi

if [[ $CH_TEST_BUILDER = ch-image ]]; then
    clrequire '"lark" module ... bundled'
    test -f ./lib/lark/lark.py
fi

clrequire 'recommended tests, tar-unpack mode: yes'
clrequire 'recommended tests, squash-unpack mode: yes'


# Build.
make -j"$(nproc)"
ldd bin/ch-run
bin/ch-run --version

# Make tarball.
rm -f charliecloud-*.tar.gz
make dist
ls -lh charliecloud-*.tar.gz

# Install.
if [[ -n $prefox ]]; then
    sudo make install
    echo "$prefox"
    ldd "$prefox"/bin/ch-run
    "$prefox"/bin/ch-run --version
fi
