#!/usr/bin/env bash

# NOTE: This script is just ext/bin/boxed-core-tests with a different
# temporary directory name.

# Run command using ephemeral Leiningen and pgbox executables, as well as
# ephemeral PuppetDB and PostgreSQL sandboxes.
# Flags --pgbin and --pgport are optional if previously set with ext/bin/test-config.
# Destroys the executables and sandboxes afterwards.
# Example: boxed-integration-tests -- lein test :integration

set -ueo pipefail

usage() {
    echo 'Usage: $(basename "$0") [--pgbin DIR] [--pgport PORT] -- CMD ...'
}

misuse() { usage 1>&2; exit 2; }

declare -A opt

# Validate arguments
while test $# -gt 0; do
    case "$1" in
        --pgbin|--pgport|--pglog)
            test $# -gt 1 || misuse
            opt["${1:2}"]="$2"
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            misuse
    esac
done
cmd=("$@")

# If pgbin directory is not provided with --pgbin, read ext/test-conf/pgbin
# If pgbin directory cannot be found, exit with error status
if test -z "${opt[pgbin]:-}"; then
    opt[pgbin]="$(ext/bin/test-config --get pgbin)"
    if test  -z "${opt[pgbin]:-}"; then
        echo 'Please specify --pgbin or set pgbin with ext/bin/test-config' 1>&2
        exit 2
    fi
fi

# If pgport number is not provided with --pgport, read ext/test-conf/pgport
# If pgport number cannot be found, exit with error status
if test -z "${opt[pgport]:-}"; then
    opt[pgport]="$(ext/bin/test-config --get pgport)"
     if test  -z "${opt[pgport]:-}"; then
        echo 'Please specify --pgport or set pgport with ext/bin/test-config' 1>&2
        exit 2
    fi
fi

set -x

# Create temporary directory
tmpdir="$(mktemp -d "int-test-XXXXXX")"
tmpdir="$(cd "$tmpdir" && pwd)"
trap "$(printf 'rm -rf %q' "$tmpdir")" EXIT
mkdir -p "$tmpdir/local"

# Install Leiningen and pgbox with default versions into temporary directory
ext/bin/require-leiningen default "$tmpdir/local"
ext/bin/require-pgbox default "$tmpdir/local"
export PATH="$tmpdir/local/bin:$PATH"
# Print host machine info for logging
ext/bin/host-info

# Run command with ephemeral PuppetDB and PostgreSQL sandbox
box_args=()
if test "${opt[pgbin]:-}"; then box_args+=(--pgbin "${opt[pgbin]}"); fi
if test "${opt[pgport]:-}"; then box_args+=(--pgport "${opt[pgport]}"); fi
if test "${opt[pglog]:-}"; then box_args+=(--pglog "${opt[pglog]}"); fi
ext/bin/with-pdbbox --box "$tmpdir/box" "${box_args[@]}" -- "${cmd[@]}"
