#!/bin/bash

function usage() {
    echo "usage: $0 {gcc|gcc-lto|gcc-pgo|gcc-instrument|clang|clang-lto|clang-pgo|clang-instrument} [clingo-args...]" >&2
    exit 1
}

[[ $# -gt 0 ]] || usage

loc="$(realpath "$(dirname "$0")")"
jemalloc_conda="$CONDA_PREFIX/lib/libjemalloc.so"
mimalloc_conda="$CONDA_PREFIX/lib/libmimalloc.so"
if [ -e "$jemalloc_conda" ]; then
    jemalloc="$jemalloc_conda"
else
    jemalloc=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2
fi
if [ -e "$mimalloc_conda" ]; then
    mimalloc="$mimalloc_conda"
else
    mimalloc=/usr/lib/x86_64-linux-gnu/libmimalloc.so.2
fi
tbbmalloc=/usr/lib/x86_64-linux-gnu/libtbbmalloc_proxy.so.2
tcmalloc=/usr/lib/x86_64-linux-gnu/libtcmalloc_minimal.so.4
dir=""

options=()
extra_options=()
for arg in "$@"; do
    case "${arg}" in
    gcc-opt)
        dir=release
        ;;
    gcc-lto)
        dir=release_lto
        ;;
    gcc-pgo)
        dir=release_pgo
        ;;
    gcc-instrument)
        dir=release_instrument
        ;;
    gcc-tbbmalloc)
        export LD_PRELOAD="${tbbmalloc}"
        dir=release_pgo
        ;;
    gcc-jemalloc)
        export LD_PRELOAD="${jemalloc}"
        dir=release_pgo
        ;;
    gcc-mimalloc)
        export LD_PRELOAD="${mimalloc}"
        dir=release_pgo
        ;;
    gcc-tcmalloc)
        export LD_PRELOAD="${tcmalloc}"
        dir=release_pgo
        ;;
    clang-opt)
        dir=release
        ;;
    clang-lto)
        dir=release_clang_lto
        ;;
    clang-pgo)
        dir=release_clang_pgo
        ;;
    clang-instrument)
        dir=release_clang_instrument
        ;;
    clang-tbbmalloc)
        export LD_PRELOAD="${tbbmalloc}"
        dir=release_clang_pgo
        ;;
    clang-jemalloc)
        export LD_PRELOAD="${jemalloc}"
        dir=release_clang_pgo
        ;;
    clang-mimalloc)
        export LD_PRELOAD="${mimalloc}"
        dir=release_clang_pgo
        ;;
    clang-tcmalloc)
        export LD_PRELOAD="${tcmalloc}"
        dir=release_clang_pgo
        ;;
    */encoding.lp)
        options+=("$arg")
        opts="$(dirname "${arg}")/options.txt"
        if [[ -e "${opts}" ]]; then
            mapfile -t extra_options <"${opts}"
        fi
        ;;
    *)
        options+=("$arg")
        ;;
    esac
done

if [[ "${dir}" == "" ]]; then
    usage
fi

exec "$loc/../../build/$dir/bin/clingo" "${options[@]}" "${extra_options[@]}"
