#!/bin/bash

declare sourcedirs=( )
declare modulesdir
declare destdir
declare destarchive
declare root
declare CPIO=cpio
declare linuxversion

# find a way to get the value of `uname -r` for the kernel
# you're building, not necessarily the one you're running
linuxversion="$(readlink /usr/src/linux)"
linuxversion="${linuxversion#linux-}"

root="/"
destdir="$HOME/initramfs_dist"
destarchive="${destdir}/initramfs-${linuxversion}.cpio"

sourcedirs+=( "/usr/src/initramfs" )
modulesdir="lib/modules/${linuxversion}"

# initialize empty archive
echo -n | $CPIO -o0 -H newc -O "${destarchive}"

# append custom directories
for sourcedir in "${sourcedirs[@]}"; do
	(
		cd "${sourcedir}" && \
		find . -print0 | $CPIO -o0A -H newc -O "${destarchive}"
	)
done

# append installed kernel modules
(
	cd "${root}" && \
	find "${modulesdir}" -print0 | $CPIO -o0A -H newc -O "${destarchive}"
)

# compress cpio archive
gzip "${destarchive}"
