#!/bin/sh

. /lib/dracut-lib.sh

[ -f /tmp/root.info ] && . /tmp/root.info

PATH=/usr/sbin:/usr/bin:/sbin:/bin

[ -z "$1" ] && exit 1
livedev="$1"

livepath=""
persistpart=""
persistfile=""
livesys="/live/media/loopbacks/distrib-lzma.sqfs"
cline=$(cat /proc/cmdline)

# create live tree
mkdir -m 0755 -p /live/media
mkdir -m 0755 -p /live/distrib
mkdir -m 0755 -p /live/memory
mkdir -m 0755 -p /live/union
mkdir -m 0755 -p /run/mgalive/ovlsize

# fix udev isohybrid LABEL issues (mga #3334)
# by reading the device we get, stripping away partition number,
# and mount the resulting device
realdev=$(echo $livedev |sed 's,\(/dev/sd[a-z]\)0,\1,g')

[[ "$cline" =~ "livepath=/" ]] && livepath=$(sed 's/.*livepath=\///' /proc/cmdline | sed 's/ .*//')
[[ "$cline" =~ "persistpartlabel=" ]] && persistpartlabel=$(sed 's/.*persistpartlabel=//' /proc/cmdline | sed 's/ .*//')
[[ "$cline" =~ "persistpartuuid=" ]] && persistpartuuid=$(sed 's/.*persistpartuuid=//' /proc/cmdline | sed 's/ .*//')
[[ "$cline" =~ "persistfile=" ]] && persistfile=$(sed 's/.*persistfile=\///' /proc/cmdline | sed 's/ .*//')

if [ -n "$livepath" ]; then
  livesys="/live/media/$livepath/loopbacks/distrib-lzma.sqfs"
fi

if [ -n "$persistfile" ]; then
  persistfile="/live/media/$livepath/$persistfile"
fi

# mount the live media
getargbool 0 UEFI && liveuefi="yes"
if [ -n "$liveuefi" ]; then
    mount -n -t vfat -o ro $livedev /live/media
else
#    mount -n -t iso9660 -o ro $realdev /live/media
    mount -n -t ext4 -o rw $realdev /live/media
fi

LOOPDEV=$( losetup -f )
losetup -r $LOOPDEV $livesys
mount -n -t squashfs -o ro $LOOPDEV /live/distrib
mount -n -t squashfs -o ro $LOOPDEV /run/mgalive/ovlsize
mount -n -t tmpfs -o mode=755 /live/memory /live/memory
mount -n -t overlayfs -o lowerdir=/live/distrib,upperdir=/live/memory overlayfs /live/union

ln -s /live/union /dev/root

printf '/bin/mount --rbind /live/union %s\n' "$NEWROOT" > $hookdir/mount/01-$$-live.sh

need_shutdown

exit 0
