#!/usr/bin/env bash

set -eu -o pipefail

SOURCE_DIR=/source
BUILD_DIR=/build
CMD=${1:-test}
shift

# build type can be "debug" or "release", fallbacks to "release" by default
BUILD_TYPE=$(echo "$BUILD_TYPE" | tr "[:upper:]" "[:lower:]")
case "$BUILD_TYPE" in
"debug")
    ;;
*)
    BUILD_TYPE="release"
    ;;
esac

build_image() {
    BUILD_DIR=$1
    BUILD_TYPE=$2
    FALCO_VERSION=$3
    PACKAGE_TYPE=$4
    PACKAGE="$BUILD_DIR/$BUILD_TYPE/falco-$FALCO_VERSION-x86_64.${PACKAGE_TYPE}"
    if [ ! -f "$PACKAGE" ]; then
        echo "Package not found: ${PACKAGE}." >&2
        exit 1
    fi
    DOCKER_IMAGE_NAME="falcosecurity/falco:test-${PACKAGE_TYPE}"
    echo "Building local docker image $DOCKER_IMAGE_NAME from latest ${PACKAGE_TYPE} package..."

    mkdir -p /runner-rootfs
    cp "$PACKAGE" /runner-rootfs
    cp -R "$SOURCE_DIR/falco/test/rules" /runner-rootfs
    cp -R "$SOURCE_DIR/falco/test/trace_files" /runner-rootfs
    docker build -f "/runners/$PACKAGE_TYPE.Dockerfile" --build-arg FALCO_VERSION="$FALCO_VERSION" -t "$DOCKER_IMAGE_NAME" /runner-rootfs
}

clean_image() {
    PACKAGE_TYPE=$1
    DOCKER_IMAGE_NAME="falcosecurity/falco:test-${PACKAGE_TYPE}"
    docker rmi -f "$DOCKER_IMAGE_NAME"
}

case "$CMD" in
"test")
    if [ -z "$FALCO_VERSION" ]; then
        echo "Automatically figuring out Falco version."
        FALCO_VERSION=$("$BUILD_DIR/$BUILD_TYPE/userspace/falco/falco" --version | head -n 1 | cut -d' ' -f3 | tr -d '\r')
        echo "Falco version: $FALCO_VERSION"
    fi
    if [ -z "$FALCO_VERSION" ]; then
        echo "Falco version cannot be guessed, please provide it with the FALCO_VERSION environment variable." >&2
        exit 1
    fi

    # build docker images
    build_image "$BUILD_DIR" "$BUILD_TYPE" "$FALCO_VERSION" "deb"
    build_image "$BUILD_DIR" "$BUILD_TYPE" "$FALCO_VERSION" "rpm"

    # check that source directory contains Falco
    if [ ! -d "$SOURCE_DIR/falco/test" ]; then
        echo "Missing $SOURCE_DIR/falco/test directory." >&2
        exit 1
    fi

    # run tests
    echo "Running regression tests ..."
    cd "$SOURCE_DIR/falco/test"
    ./run_regression_tests.sh "$BUILD_DIR/$BUILD_TYPE"

    # clean docker images
    clean_image "deb"
    clean_image "rpm"
    ;;
"bash")
    CMD=/bin/bash
    ;& # fallthrough
"usage")
    exec "$CMD" "$@"
    ;;
esac
