#!/bin/bash

set -e

NAME=amdgpu
PACKAGE_NAME=amdgpu-dkms
CVERSION=5.16.9.22.20-1438747~22.04
ARCH=$(uname -m)

dkms_configure () {
	local rc
	local name mver kver arch status

	for POSTINST in /usr/lib/dkms/common.postinst "/usr/share/$PACKAGE_NAME/postinst"; do
		if [ -f "$POSTINST" ]; then
			#
			# Prevent modprobe amdgpu by DKMS that may cause black screen during
			# installation:
			#    1. Blacklist amdgpu and disable initramfs regeneration
			#    2. Build and install amdgpu kernel module
			#    3. Remove amdgpu from blacklist and re-enable initramfs regeneration
			#    4. Install an initramfs hook that copies F/W to the early initramfs
			#    5. Generate new initramfs
			#
			echo "blacklist amdgpu" >/etc/modprobe.d/blacklist-amdgpu.conf
			sed -i "s/\(REMAKE_INITRD=\).*/\1\"no\"/" /usr/src/$NAME-*/dkms.conf
			"$POSTINST" "$NAME" "$CVERSION" "/usr/share/$PACKAGE_NAME" "$ARCH" "$2" || true
			rc=$?
			sed -i "s/\(REMAKE_INITRD=\).*/\1\"yes\"/" /usr/src/$NAME-*/dkms.conf
			rm -f /etc/modprobe.d/blacklist-amdgpu.conf
			if [ $rc -eq 0 ]; then
				#
				# Different versions of dkms may format output of the status differently,
				# for example:
				#
				#  amdgpu, <version>, <kernel version>, x86_64: installed
				#  amdgpu/<version>, <kernel version>, x86_64: installed (<comments>)
				#
				# To handle it correctly we use a multi-separator for `read' function to
				# make sure the kernel version is always in the field #3. The rest of the
				# output appears in `status' variable that has to contain `installed'
				# sub-string.
				#
				while IFS=" /," read name mver kver status; do
					if [ -z "${status##*installed*}" ]; then
						update-initramfs -u -k $kver
					fi
				done<<<$(dkms status $NAME/$CVERSION)
			fi
			return $rc
		fi
		echo "WARNING: $POSTINST does not exist." >&2
	done
	echo "ERROR: DKMS version is too old and $PACKAGE_NAME was not" >&2
	echo "built with legacy DKMS support." >&2
	echo "You must either rebuild $PACKAGE_NAME with legacy postinst" >&2
	echo "support or upgrade DKMS to a more current version." >&2
	return 1
}

case "$1" in
	configure)
		dkms_configure
		;;

	abort-upgrade|abort-remove|abort-deconfigure)
		;;

	*)
		echo "postinst called with unknown argument \`$1'" >&2
		exit 1
		;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.



exit 0
