#!/bin/bash
#
# Compile the Linux kernel under Syd under Perf.
#
# Copyright 2024 Ali Polatel <alip@chesswob.org>
#
# SPDX-License-Identifier: GPL-3.0

if [[ ${#} -lt 1 ]]; then
    echo >&2 "Usage: ${0##*/} <perf-arguments>..."
    exit 1
fi

# Make sure we don't trigger TPE.
umask 077

# Disable coredumps.
ulimit -c 0

SYD="${CARGO_BIN_EXE_syd:-syd}"
PERF="${PERF:-perf}"
PROF="${SYD_PERF_PROFILE:-paludis}"

DIR="$(mktemp -d --tmpdir=/tmp syd-lnx.XXXXXXXXXX)"
[[ -d "${DIR}" ]] || exit 2

CWD=$(readlink -f ${PWD})
trap "mv '${DIR}'/git/perf.data* '${CWD}' &>/dev/null && rm -rf '${DIR}'" INT TERM EXIT
set -ex

pushd "${DIR}"
git clone --depth 1 https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git

pushd linux
rm -f /tmp/syd.pid
export SYD_PID_FN=/tmp/syd.pid
"${PERF}" "${@}" -- \
    "${SYD}" -q -p"${PROF}" -pP -m 'allow/all+/***' -mlock:on \
        -- \
        sh -cex 'make defconfig && make -j$(nproc) && make clean'
