#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PATH="$ROOT/third-party/bin:$ROOT/third-party:$ROOT/third-party/veripb/bin:$ROOT/third-party/veripb:${PATH:-}"

install_binary_tool() {
    local tool="$1"
    local pattern="$2"
    if command -v "$tool" >/dev/null 2>&1; then
        return
    fi

    shopt -s nullglob
    local archives=($pattern)
    shopt -u nullglob
    if (( ${#archives[@]} == 0 )); then
        echo "$tool is not available and no binary archive matching $pattern exists" >&2
        exit 2
    fi

    tar -xzf "${archives[0]}" -C "$ROOT/third-party" --strip-components=1
    if ! command -v "$tool" >/dev/null 2>&1; then
        echo "$tool archive ${archives[0]} did not install $tool on PATH" >&2
        exit 2
    fi
}

install_cmake() {
    install_binary_tool cmake "$ROOT/third-party/cmake-*-linux-x86_64.tar.gz"
}

install_veripb() {
    shopt -s nullglob
    local archives=("$ROOT"/third-party/veripb-*-linux-x86_64.tar.gz)
    shopt -u nullglob
    if (( ${#archives[@]} == 0 )); then
        return
    fi
    if command -v veripb >/dev/null 2>&1 || [[ -x "$ROOT/third-party/bin/veripb" ]]; then
        return
    fi
    install_binary_tool veripb "$ROOT/third-party/veripb-*-linux-x86_64.tar.gz"
}

install_compiler_wrappers() {
    if command -v ld.lld >/dev/null 2>&1 || command -v lld >/dev/null 2>&1; then
        return
    fi

    local wrapper_dir="$ROOT/third-party/compiler-wrappers"
    mkdir -p "$wrapper_dir"
    cat > "$wrapper_dir/clang++" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
real="${LYMPHOSAT_REAL_CLANGXX:-/usr/bin/clang++}"
args=()
for arg in "$@"; do
    [[ "$arg" == "-fuse-ld=lld" ]] && continue
    args+=("$arg")
done
exec "$real" "${args[@]}"
EOF
    cat > "$wrapper_dir/clang" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
real="${LYMPHOSAT_REAL_CLANG:-/usr/bin/clang}"
args=()
for arg in "$@"; do
    [[ "$arg" == "-fuse-ld=lld" ]] && continue
    args+=("$arg")
done
exec "$real" "${args[@]}"
EOF
    chmod +x "$wrapper_dir/clang++" "$wrapper_dir/clang"
    export PATH="$wrapper_dir:$PATH"
}

install_cmake
install_veripb
install_compiler_wrappers

cd "$ROOT/solver"
chmod +x ./generic-build.sh
./generic-build.sh
