#!/bin/bash

# this script is a dirty hack to provide dkms kernel module builds for linux-rpi from graysky's repository
# kernel and headers are build with cross-compiler which impacts binaries in linux-rpi-headers package
# which are now x86-64 and block the possibility to build dkms modules out-of-the-box
# A simple hack is to swap the x86-64 binaries with the aarch64 ones from mainline linux-rpi-headers,
# build dkms modules and swap the ones belonging to graysky's linux-rpi-headers back to their place so
# that package integrity is guaranteed.
#
# License GPLv3, written by Andreas Richter (DF8OE). You can use this script without any guarantee!


actver=$(pacman -Qs linux-rpi-headers | cut -d " " -f 2)
mpath="/usr/lib/modules/$actver-rpi-ARCH/build/scripts/"
rpath="/lib/modules/linux-rpi-headers-scripts/"

echo "...backup (x86-64) linux-headers-rpi-binary-helpers to /tmp..."
mkdir /tmp/scripts
mkdir /tmp/scripts/basic/
mkdir /tmp/scripts/dtc/
mkdir /tmp/scripts/kconfig/
mkdir /tmp/scripts/mod/
cp $mpath/basic/fixdep /tmp/scripts/basic/
cp $mpath/dtc/dtc /tmp/scripts/dtc/
cp $mpath/dtc/fdtoverlay /tmp/scripts/dtc/
cp $mpath/kconfig/conf /tmp/scripts/kconfig/
cp $mpath/mod/mk_elfconfig /tmp/scripts/mod/
cp $mpath/mod/modpost /tmp/scripts//mod/
cp $mpath/asn1_compiler /tmp/scripts/
cp $mpath/kallsyms /tmp/scripts/
cp $mpath/sorttable /tmp/scripts/

echo "...overwrite x86-64 binaries with aarch64 binaries from mainline linux-rpi-headers package..."
cd $rpath
cp -rf * $mpath

echo "...build dkms modules for running kernel"
dkms autoinstall

echo "...copy backuped binaries back..."
cd /tmp/scripts/
cp -rf * $mpath

echo "...remove temporary backuped executables..."
rm -rf /tmp/scripts

echo "...successfully finished!"
