#!/bin/bash
set -xeuo pipefail

# set to 1 to enable profiling
profile=

_build() {
    if [[ "$profile" == 1 ]]; then
        perf=(perf record --call-graph=dwarf -g -o "$HOME/$name.data")
    else
        perf=()
    fi

    name=$1
    shift
                 bazel         build    --color=no --curses=no "$@" //:zigzag-0
                 bazel         clean    --color=no --curses=no
                 bazel         shutdown --color=no --curses=no
     ( "${perf[@]}" bazel --batch build --color=no --curses=no "$@" ... ) |& \
         tee "results/${name}.log"
}

_build zigcc-nosandbox          --spawn_strategy=local                    --platforms=@zig_sdk//libc_aware/platform:linux_amd64_gnu.2.28
_build llvm-nosandbox           --spawn_strategy=local                    --extra_toolchains=@llvm_toolchain_with_sysroot//:cc-toolchain-x86_64-linux
_build zigcc                                                              --platforms=@zig_sdk//libc_aware/platform:linux_amd64_gnu.2.28
_build llvm                                                               --extra_toolchains=@llvm_toolchain_with_sysroot//:cc-toolchain-x86_64-linux
_build zigcc-reuse-sandbox-dirs  --experimental_reuse_sandbox_directories --platforms=@zig_sdk//libc_aware/platform:linux_amd64_gnu.2.28
_build llvm-reuse-sandbox-dirs   --experimental_reuse_sandbox_directories --extra_toolchains=@llvm_toolchain_with_sysroot//:cc-toolchain-x86_64-linux

if [[ $profile == 1 ]]; then
    for d in $HOME/*.data; do
        f=$(basename "$d")
        echo "perf script -i $d | inferno-collapse-perf | inferno-flamegraph > results/${f%data}svg"
    done | parallel -v --eta
fi
