#!/usr/bin/env bash

set -eu

# Use the stubs, not the system user{mod,add} binaries. Since we don't know how exactly the bb
# tests will be run and where the stubs will be located, rely on the bb test caller setting up
# their PATH to include them. We don't need to include `id` because it gets copied into the
# system
GLDFLAGS="-X github.com/coreos/ignition/v2/internal/distro.useraddCmd=useradd-stub "
GLDFLAGS+="-X github.com/coreos/ignition/v2/internal/distro.usermodCmd=usermod-stub "
GLDFLAGS+="-X github.com/coreos/ignition/v2/internal/distro.userdelCmd=userdel-stub "
GLDFLAGS+="-X github.com/coreos/ignition/v2/internal/distro.groupaddCmd=groupadd-stub "
GLDFLAGS+="-X github.com/coreos/ignition/v2/internal/distro.groupmodCmd=groupmod-stub "
GLDFLAGS+="-X github.com/coreos/ignition/v2/internal/distro.groupdelCmd=groupdel-stub "
GLDFLAGS+="-X github.com/coreos/ignition/v2/internal/distro.blackboxTesting=true "

REPO_PATH="github.com/coreos/ignition/v2"

eval $(go env)
if [ -z ${BIN_PATH+a} ]; then
	export BIN_PATH=${PWD}/bin/${GOARCH}
fi

export GLDFLAGS

echo "Building ignition for blackbox tests..."
make ignition BIN_PATH=${BIN_PATH}

PKG=$(go list ./tests/)

echo "Compiling tests..."
go test -c $PKG

for D in tests/stubs/*; do
	if [ -d "${D}" ]; then
		echo "Building ${D}"
		go build -o ${BIN_PATH}/$(basename ${D}) ${REPO_PATH}/${D}
	fi
done

echo "Success"
