#!/bin/sh

[ "$#" -lt 1 ] && exit 0

# copied from alpine-conf/setup-disk.in
_blkid() {
	blkid | grep "^$1:"
}
uuid_or_device() {
	local i=
	case "$1" in
		/dev/md*) echo "$1" && return 0;;
	esac
	for i in $(_blkid "$1"); do
		case "$i" in
			UUID=*) eval $i;;
		esac
	done
	if [ -n "$UUID" ]; then
		echo "UUID=$UUID"
	else
		echo "$1"
	fi
}
find_mount_dev() {
	local mnt="$1"
	awk "\$2 == \"$mnt\" { print \$1 }" /proc/mounts | tail -n 1
}

zipl_gen_conf() {
	KERNEL_FLAVOR="-vanilla"
	RAMDISK_FLAVOR="-vanilla"
	
	rootdev=$(find_mount_dev "/")
	root_uuid=$(uuid_or_device $rootdev)
	[ -n "$root_uuid" ] && root_parm="root=$root_uuid"

	cat > /etc/zipl.conf <<- EOF
	[defaultboot]
	defaultauto
	prompt=1
	timeout=5
	default=linux
	target=/boot
	[linux]
		image=/boot/vmlinuz$KERNEL_FLAVOR
		ramdisk=/boot/initramfs$RAMDISK_FLAVOR
		parameters="$root_parm rd.md=0 rd.dm=0 rd.luks=0 KEYTABLE=us LANG=en_US.UTF-8"
	EOF
}

zipl_run() {
	zipl_gen_conf
	/sbin/zipl --verbose
}

"$1"

