#!/bin/sh
set -e

# Play nice when run under debconf.
exec </dev/null >&2

version="$1"

# passing the kernel version is required
if [ -z "${version}" ]; then
	echo >&2 "W: u-boot-fdtdir-dtb: ${DPKG_MAINTSCRIPT_PACKAGE:-kernel package} did not pass a version number"
	exit 2
fi

dtb_path="/usr/lib/linux-image-${version}"
if [ -e "/usr/lib/modules/${version}/dtb" ] ; then
	dtb_path="/usr/lib/modules/${version}/dtb/"
else
	dtb_path="/usr/lib/linux-image-${version}/"
fi
boot_dtb_base_path="/boot/dtbs/"
boot_dtb_path="${boot_dtb_base_path}/linux-image-${version}"

# avoid running multiple times
if [ -n "$DEB_MAINT_PARAMS" ]; then
	eval set -- "$DEB_MAINT_PARAMS"
	if [ -z "$1" ] || [ "$1" = "configure" ]; then
		mkdir -p ${boot_dtb_base_path}
		if test -d "${dtb_path}" ; then
			echo "uboot-fdtdir-dtb: Update ${version} dtb"
			cp -RT ${dtb_path} ${boot_dtb_path}
		fi
	elif [ -z "$1" ] || [ "$1" = "remove" ]; then
		if test -d "${boot_dtb_path}" ; then
			echo "uboot-fdtdir-dtb: Remove ${version} dtb"
			rm -rf ${boot_dtb_path}
		fi
	fi
fi
