#!/bin/bash

unamer="${1}"

# When the kernel package has itb, extract Image.gz and Image from it
# Extract the name of linuxpkg differently
if [[ "${2##*.}" == "itb" ]]; then
  linuxpkg="linux-image-${unamer}" # from altered mkdebian
  dumpimage -T flat_dt -o /boot/Image-${linuxpkg}.gz "${2}"
  (cd /boot; gunzip Image-${linuxpkg}.gz)
else
  linuxpkg="${2#*Image-}"
fi

# When the kernel package has dtbs at /lib/modules/$(uname -r)/dtbs/
# Copy them to "/boot/dtbs/${linuxpkg}/" where we expect them
dtbsdir="/usr/lib/${linuxpkg}"
[ ! -d "${dtbsdir}" ] && dtbsdir="/lib/modules/${unamer}/dtbs"
if [ -d "${dtbsdir}" ]; then
  mkdir -p "/boot/dtbs/${linuxpkg}"
  cp -vft  "/boot/dtbs/${linuxpkg}" "${dtbsdir}/"*"/"*
fi

if [ ! -f "/lib/modules/${unamer}/pkgbase" ]; then
  echo -n "${linuxpkg}" >/lib/modules/${unamer}/pkgbase
fi

echo ">>> Updating module dependencies for ${unamer}. Please wait ..."
depmod "${unamer}"

bpir-toolbox --write2dtb --write2fip --pkgbase="${linuxpkg}"

exit 0
