#!/bin/sh
# SPDX-License-Identifier: LGPL-2.1-or-later
set -e

if [ -d "$SRCDIR"/mkosi.kernel/ ]; then
    SRCDIR="$SRCDIR/mkosi.kernel"
    BUILDDIR="$BUILDDIR/mkosi.kernel"
    cd "$SRCDIR"
    mkdir -p "$BUILDDIR"

    # Ensure fast incremental builds by fixating these values which usually change for each build.
    export KBUILD_BUILD_TIMESTAMP="Fri Jun  5 15:58:00 CEST 2015"
    export KBUILD_BUILD_HOST="mkosi"

    scripts/kconfig/merge_config.sh -O "$BUILDDIR" \
            ../mkosi.kernel.config \
            tools/testing/selftests/bpf/config.x86_64 \
            tools/testing/selftests/bpf/config

    # Make sure systemd-boot boots this kernel and not the distro provided one by overriding the version.
    make O="$BUILDDIR" VERSION=99 -j "$(nproc)"

    KERNEL_RELEASE=$(make O="$BUILDDIR" VERSION=99 -s kernelrelease)
    mkdir -p "$DESTDIR/usr/lib/modules/$KERNEL_RELEASE"
    make O="$BUILDDIR" VERSION=99 INSTALL_MOD_PATH="$DESTDIR/usr" modules_install
    make O="$BUILDDIR" VERSION=99 INSTALL_PATH="$DESTDIR/usr/lib/modules/$KERNEL_RELEASE" install
    mkdir -p "$DESTDIR/usr/lib/kernel/selftests"
    make -C tools/testing/selftests -j "$(nproc)" O="$BUILDDIR" VERSION=99 KSFT_INSTALL_PATH="$DESTDIR/usr/lib/kernel/selftests" SKIP_TARGETS="" install

    mkdir -p "$DESTDIR"/usr/bin
    ln -sf /usr/lib/kernel/selftests/bpf/bpftool "$DESTDIR/usr/bin/bpftool"
fi
