#!/bin/bash
#
# This script runs ci/build in a Docker container.

if [ $# -eq 0 ] || [ ${1:-} = -h ] || [ ${1:-} = --help ]; then
    cat <<EOF
Usage: build-in-docker NAME [ARGUMENTS]

NAME: Subdirectory name in the dockerfiles directory.
ARGUMENTS: Arguments that will be passed to ci/build.
EOF
    exit 1
fi

set -eu

if [ -n "${VERBOSE:-}" ]; then
    set -x
fi

name=${1}
shift

tag="ccache-build:$name"
command="${COMMAND:-/source/ci/build}"
interactive="${INTERACTIVE:+--interactive --tty}"

# Build (if not exists):
docker build -t "$tag" "dockerfiles/$name"

# Cache compilation across docker sessions
mkdir -p build-in-docker
mkdir -p build-in-docker/docker-ccache

docker run \
    --rm \
    --volume "$PWD:/source" \
    --volume "$PWD/build-in-docker/docker-ccache:/ccache" \
    --tmpfs /builddir:rw,exec \
    --workdir /builddir \
    --env ASAN_OPTIONS="${ASAN_OPTIONS:-}" \
    --env EXTRA_CMAKE_BUILD_FLAGS="${EXTRA_CMAKE_BUILD_FLAGS:-}" \
    --env CC="${CC:-}" \
    --env CCACHE_DIR=/ccache \
    --env CCACHE_LOC="/source" \
    --env CFLAGS="${CFLAGS:-}" \
    --env CMAKE_PARAMS="${CMAKE_PARAMS:-}" \
    --env CXX="${CXX:-}" \
    --env CXXFLAGS="${CXXFLAGS:-}" \
    --env LDFLAGS="${LDFLAGS:-}" \
    --env NO_TEST="${NO_TEST:-}" \
    --env SCAN_BUILD="${SCAN_BUILD:-}" \
    --env SPECIAL="${SPECIAL:-}" \
    --env VERBOSE="${VERBOSE:-}" \
    $interactive \
    "$tag" \
    "$command" "$@"
