#!/bin/sh

PREREQ=""

prereqs()
{
	echo "$PREREQ"
}

case $1 in
prereqs)
	prereqs
	exit 0
   	;;
esac

# Fonctions initramfs-tools
. /scripts/functions

# Variable $ROOT définie par le processus init, correspondant à l'argument
# root= de la ligne de commande kernel
log_begin_msg "Attach Squashfs to ${ROOT}"

# Récupère l'argument squashfs.partlabel pour idenfitier la partition
partlabel=$(cat /proc/cmdline | sed -nr -e 's/.*squashfs\.partlabel=([^= ]+).*/\1/p')
if [ -z "$partlabel" ] ; then
	panic "Squashfs partlabel not specified. Boot arguments must include a squashfs.partlabel= parameter"
fi

# Récupère le device associé à la partition
dev="$(realpath "/dev/disk/by-partlabel/${partlabel}")"
if [ $? -ne 0 ] ; then
	panic "Partlabel '${partlabel}' not found"
fi

# Montage de la partition
mkdir /mnt
mount $dev /mnt -t ext4

# Récupère l'argument squashfs.file pour le nom du fichier Squashfs
file=$(cat /proc/cmdline | sed -nr -e 's/.*squashfs\.file=([^= ]+).*/\1/p')
if [ -z "$file" ] ; then
	panic "Squashfs file not specified. Boot arguments must include a squashfs.file= parameter"
fi

if [ ! -f "/mnt/${file}" ] ; then
	panic "Could not find the Squashfs file ${file}"
fi

# Associe le fichier Squashfs au loop device passé en argument root
if losetup $ROOT /mnt/${file} ; then
	log_success_msg "Squashfs attached to ${ROOT} with success"
else
	panic "Could not attach the Squashfs to ${ROOT}"
fi

log_end_msg

exit 0