#!/bin/bash

# Build all the configured benchmarks for the provided project
# Expects the first argument to be the path to a project th

set -e

# Get the desired optimization level if specified
if [[ -z "${OPT_LEVEL}" ]]; then
    # Default OPT level
    OPT_LEVEL_ARG="-DOPT_LEVEL=-O1"
else
    OPT_LEVEL_ARG="-DOPT_LEVEL=${OPT_LEVEL}"
fi

#
# The base target configuration for intermittent computing
#

BASE_ICLANG_CODEGEN_FLAGS=""

#
# The different target configurations
#

# Uninstrumented
# Does not perform any transformations but does go trough the pipeline
function uninstrumented() {
    # Configure the benchmark
    export ICLANG_NO_PASSES="YES"

    # Build the benchmark
    build_benchmark "${FUNCNAME[0]}"
}

# Cache Hint
# Applies the cache hint transformations
function cachehints() {
    # Build the benchmark
    build_benchmark "${FUNCNAME[0]}"
}


# All regular targets are above
funcs=$(declare -F)
targets="${funcs//declare -f /}"


function help() {
    echo "Usage: benchmark-build [target]"
    echo ""
    echo "targets: (bash functions in this script)"
    echo "${funcs//declare -f/ }"

    # Other
    echo ""
    echo "other:"
    echo "  help       print this help message"
    echo "  targets    print all the available targets"
}

function targets() {
    echo $targets
}


# Build the benchmark using the environment variables set in the targets
CMAKE_TOOLCHAIN_FILE="$ICLANG_ROOT/toolchains/riscv32/toolchain.cmake"
function build_benchmark() {
    local benchmark_name="$1"
    local build_dir="build-$benchmark_name"
    echo "Building benchmark $benchmark_name in $build_dir"

    rm -rf "$build_dir"
    mkdir -p "$build_dir"
    pushd "$build_dir"

    cmake $OPT_LEVEL_ARG -DCMAKE_TOOLCHAIN_FILE="$CMAKE_TOOLCHAIN_FILE" ../
    make

    popd
}

target="$1"
if [ -z "$1" ]; then
    echo "Please provide a target (bash function)"
    help
    exit 1
fi

# Run the function that generates the target
if [[ $(type -t $target) == function ]]; then
    $target "$target"

elif [[ $target =~ loop-unroll-.+ ]]; then
    cnt="${target//loop-unroll-/}"
    loop-unroll "$cnt"

else
    echo "Target '$target' does not exist"
    help
    exit
fi


