#!/bin/bash

set -e
if [[ -n "$CI" ]]; then set -x; fi

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT="$(dirname $DIR)"

if [[ -t 1 ]]; then
    interactive='-it'
else
    interactive=''
fi

image=$(awk -F= '/org.opencontainers.image.name/ { print $2 }' < Dockerfile)

COMMAND=$1
case $COMMAND in
    *)
        image="${image}:testing"
        if [[ -n "$CI" ]]; then
            opts='--cache-from type=gha --cache-to type=gha,mode=max'
        else
            opts='--quiet'
        fi
        docker buildx build --output type=docker $opts \
               --target testing --tag $image $ROOT
        docker run --rm ${interactive} \
               --volume $ROOT:/app \
               --entrypoint pytest \
               $image /app/src "$@"
    ;;
esac
