#!/usr/bin/env bash
#
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

: ${PROFILE:="perf"}

function main {
    local additional_flags=()
    if [ "$PROFILE" = "dev" ] || [ "$PROFILE" = "debug" ]; then
        PROFILE="debug"
    else
        additional_flags+=(--profile "$PROFILE")
        # We have to disable avx512 because valgrind does not yet support it.
        export RUSTFLAGS="-C target-feature=-avx512"
    fi

    (cd "$DIR/../" && RUSTFLAGS="-C target-cpu=x86-64-v3" cargo build --no-default-features "${additional_flags[@]}")
    valgrind --tool=callgrind --callgrind-out-file="$DIR/../callgrind.out" "$DIR/../target/${PROFILE}/parse" "${@}"

    echo "You probably want to run:"
    echo "callgrind_annotate --auto=yes '$DIR/../callgrind.out'"
}

main "${@}"