#
# The Raspberry Pi build script
# Copied from `linux-kernel' build.
#

# RPi4 kernel build starts.

abinfo "Building kernel for Raspberry Pi 4."

abinfo "Copying config and setting up env..."

cp -v autobuild/config-rpi4 "$SRCDIR"/.config

. autobuild/build-common/set-var

abinfo "Verifying kernel config ..."
make olddefconfig
kernel-sort-config .config
diff autobuild/config-rpi4 .config

abinfo "Building kernel..."
make

abinfo "Stripping symbols..."
. autobuild/build-common/strip-modules

abinfo "Installing modules..."
mkdir -p "$PKGDIR"/usr
make INSTALL_MOD_PATH="$PKGDIR"/usr modules_install

abinfo "Copying kernel..."
mkdir -p "$PKGDIR"/usr/lib/rpi64/kernel/"$version"/overlays
install -Dvm755 "$SRCDIR"/arch/arm64/boot/Image "$PKGDIR"/usr/lib/rpi64/kernel/"$version"/kernel8.img

abinfo "Removing the unnecessary firmware in PKGDIR ..."
rm -rf "$PKGDIR"/usr/lib/firmware

abinfo "Extracting headers..."
. autobuild/build-common/ext-hdr

export LOCALNAME_RPI4=$LOCALNAME
unset LOCALNAME

# RPi4 kernel build ends.

abinfo "Removing all generated files + config + various backup files..."
make mrproper

# RPi5 kernel build starts.

abinfo "Building kernel for Raspberry Pi 5."

abinfo "Copying config and setting up env..."

cp -v autobuild/config-rpi5 "$SRCDIR"/.config

. autobuild/build-common/set-var

abinfo "Verifying kernel config ..."
make olddefconfig
kernel-sort-config .config
diff autobuild/config-rpi5 .config

abinfo "Building kernel..."
make

abinfo "Stripping symbols..."
. autobuild/build-common/strip-modules

abinfo "Installing modules..."
mkdir -p "$PKGDIR"/usr
make INSTALL_MOD_PATH="$PKGDIR"/usr modules_install

abinfo "Copying kernel..."
mkdir -p "$PKGDIR"/usr/lib/rpi64/kernel/"$version"/overlays
install -Dvm755 "$SRCDIR"/arch/arm64/boot/Image "$PKGDIR"/usr/lib/rpi64/kernel/"$version"/kernel_2712.img

abinfo "Removing the unnecessary firmware in PKGDIR ..."
rm -rvf "$PKGDIR"/usr/lib/firmware

abinfo "Extracting headers..."
. autobuild/build-common/ext-hdr

export LOCALNAME_RPI5=$LOCALNAME

# RPi5 kernel build ends.

# Copies the dtbs and overlays.

# Note: This can be used by both RPi4 and RPi5.
# Only copy after both RPi4 and RPi5 kernels and modules were copied.

abinfo "Copying new device tree and overlays to /usr/lib/rpi64/kernel..."
cp -v "$SRCDIR"/arch/arm64/boot/dts/broadcom/*.dtb "$PKGDIR"/usr/lib/rpi64/kernel/"$version"/
cp -rv "$SRCDIR"/arch/arm64/boot/dts/overlays/*.dtb* "$PKGDIR"/usr/lib/rpi64/kernel/"$version"/overlays/

. autobuild/build-common/gen-scripts
