#!/bin/sh
# First boot: make the initramfs again for this machine only (MODULES=dep).
# The image ships an initramfs with most drivers, so it boots on any machine.
# Run it as the initramfs-tools trigger: dpkg holds its lock for the whole
# rebuild, so a package job cannot run update-initramfs at the same time.
dpkg-trigger --no-await update-initramfs || exit 1
# While a package job has the lock, try again. Give up after 1 h:
# the service stays enabled and runs again at the next boot.
tries=0
while :; do
	# A failed rebuild leaves initramfs-tools half-configured. Configure it again.
	action=--triggers-only
	[ "$(dpkg-query -W -f '${db:Status-Status}' initramfs-tools)" = half-configured ] && action=--configure
	{ err=$(dpkg "$action" initramfs-tools 2>&1 1>&3); rc=$?; } 3>&1
	[ "$rc" = 0 ] && break
	# Lock failure: the status is not reliable without the lock. Try again.
	case "$rc:$err" in
	2:*lock*)
		tries=$((tries + 1))
		[ "$tries" -lt 360 ] || { echo "$err" >&2; exit 1; }
		sleep 10
		continue
		;;
	esac
	# "installed": a package job has run the trigger first, with success.
	if [ "$(dpkg-query -W -f '${db:Status-Status}' initramfs-tools)" = installed ]; then
		rc=0
		break
	fi
	echo "$err" >&2
	break
done
[ "$rc" = 0 ] && systemctl disable armbian-initramfs-dep.service
