#!/bin/ash

livelabel=`echo $sys | cut -f1 -d:`
livedir=`echo $sys | cut -f2 -d:`
homelabel=$home

source /etc/init.d/rcLive.inc
echo ""
echo "*** Live system initialization ***"
mkdir /live
mount -t tmpfs tmpfs /live

#mount live media
mkdir /live/media
mediadetected="none"
if [ ! -z "$ip" ]; then
	address=`echo $ip | cut -f1 -d:`
	netmask=`echo $ip | cut -f4 -d:`
	gateway=`echo $ip | cut -f3 -d:`
	sleeptime=0
	while [ "$mediadetected" = "none" ] && [ "$sleeptime" != "10" ]; do #try each seconds, but don't wait (ethernet driver) more than 10 seconds
		if ip link show | grep -q " eth0:"; then
			ip link show; sleep 1
			mediadetected="nfs"
			ip link set eth0 up
			ip addr add $address/$netmask dev eth0
			ip route add default via $gateway
			echo "NFS: $livelabel:`dirname $livedir`"
			mount -t nfs -o nolock $livelabel:`dirname $livedir` /live/media || error="set"
			livedir=`basename $livedir`
		else
			mdev -s
			sleep 1
			let sleeptime+=1
		fi
	done
else
	sleeptime=0
	while [ "$mediadetected" = "none" ] && [ "$sleeptime" != "10" ]; do #try each seconds, but don't wait (USB) more than 10 seconds
		if blkid | grep -q "\"$livelabel\""; then
			livedevice=`blkid | grep "\"$livelabel\"" | sed -n 1p | cut -f1 -d: | cut -c6-` #LABEL/UUID -> device
			if [ -d /sys/block/$livedevice ] && grep -q "1" /sys/block/$livedevice/ro
			then mediadetected="cd"
			else mediadetected="sd"	
			fi
			livedevice="/dev/$livedevice"
			echo "$livelabel found on $livedevice"
			mount -o ro $livedevice /live/media || error="set"
		else
			mdev -s
			sleep 1
			let sleeptime+=1
		fi
	done
fi
if [ "$mediadetected" = "none" ] || [ "$error" = "set" ]; then 
	echo -e "\nError: $livelabel not reachable"
	setsid sh -c 'exec sh </dev/tty1 >/dev/tty1 2>&1'
fi

#detect modules and mount squashfs ones in /live/modules/*
mkdir /live/modules
modulescount=0
if [ `ls /live/media/$livedir/modules | wc -l` != 0 ]; then
	for module in /live/media/$livedir/modules/*; do
		modulename=`basename $module`
		if ! echo $exclude | sed 's/:/\n/g' | grep -q "^$modulename$"; then
			modulescount=$(($modulescount+1))
			modulesbranches="/live/modules/$modulename:$modulesbranches"
			echo "Loading SquashFS module $modulename"
			mkdir /live/modules/$modulename
			#if needed, create additional loop device (Arch Linux):
			loopdevice=`losetup -f`
			if [ ! -b $loopdevice ]; then
				minor=`echo $loopdevice | cut -c10-`
				mknod $loopdevice b 7 $minor
			fi
			mount -o loop -t squashfs $module /live/modules/$modulename 2>/dev/null
		fi
	done
fi
modulesbranches=`echo $modulesbranches | sed 's/:$//'`
if [ $modulescount = 0 ]; then 
	echo -e "\nError: no module has been loaded"
	setsid sh -c 'exec sh </dev/tty1 >/dev/tty1 2>&1'
fi

#mount (union) all modules in /live/system (ro)
mkdir /live/system
if [ $modulescount = 1 ]
then mount --bind $modulesbranches /live/system
else mount -t overlay -o ro,lowerdir=$modulesbranches overlay /live/system
fi

#mount (union) all modules (ro) and /live/changes (rw) in /live/union (rw)
mkdir /live/.workdir
mkdir /live/changes
#~ mkdir -p /mnt
mount -t overlay -o workdir=/live/.workdir,upperdir=/live/changes,lowerdir=$modulesbranches overlay /mnt

#setup system tree
mkdir -p /mnt/tmp
mkdir -p /mnt/sys
mkdir -p /mnt/proc
mkdir -p /mnt/dev
mkdir -p /mnt/live
cat > /mnt/etc/fstab << END
proc /proc proc defaults 0 0
sysfs /sys sysfs defaults 0 0
tmpfs /dev/shm tmpfs defaults 0 0
none / tmpfs defaults 0 0
END

tweak_system

#enable persistent wifi
cat > /mnt/usr/bin/live-system-wifi.sh << EOF
#!/bin/bash
CONFIGDIR="/home/.cfg/wifi"
case "\$1" in
"start")
    if (( \$(ls \$CONFIGDIR 2>/dev/null | wc -l) != 0 )); then
        for cnx in \$CONFIGDIR/*; do
            id=\$(basename "\$cnx")
            psk=\$(cat "\$cnx")
            ( sleep 10; nmcli dev wifi connect "\$id" password "\$psk" ) &
        done
    fi
    ;;
"stop")
    if (( \$(ls /etc/NetworkManager/system-connections 2>/dev/null | wc -l) != 0 )); then
        mkdir -p \$CONFIGDIR
        for cnx in /etc/NetworkManager/system-connections/*; do
            id=\$(cat "\$cnx" | grep "^id=" | cut -f2 -d=)
            psk=\$(cat "\$cnx" | grep "^psk=" | cut -f2 -d=)
            echo "\$psk" > "\$CONFIGDIR/\$id"
        done
    fi
    ;;
esac
EOF
chmod +x /mnt/usr/bin/live-system-wifi.sh
enable_persistent_wifi

#setup persistent homedir
if [ "$mediadetected" = "nfs" ]; then
	if echo $homelabel | grep -q ":" && mount -t nfs -o nolock $homelabel /mnt/home; then
		echo "$homelabel /home nfs nolock 0 0" >> /mnt/etc/fstab
	fi
else
	homedevice=`blkid | grep "\"$homelabel\"" | sed -n 1p | cut -f1 -d:` #LABEL/UUID -> device
	if [ ! -z "$homedevice" ] && mount $homedevice /mnt/home; then
		fstype=`mount | grep $homedevice | cut -f5 -d' '`
		echo "$homedevice /home $fstype defaults,noatime 0 0" >> /mnt/etc/fstab
	fi
fi

#mtab + bind mounts
mount | sed -e 's/on //' -e 's/type //' -e 's/[()]//g' -e 's/$/ 0 0/' -e 's@overlay /mnt@overlay /@' > /mnt/etc/mtab
mount -o rbind /live /mnt/live

#system i18n setup
setup_locale
setup_time
setup_console_keymap
if [ ! -z "$keymap" ]; then
	xkblayout=`echo $keymap | cut -c1-2`
	if [ -d /mnt/etc/X11/xorg.conf.d ]; then
		echo "Setting up Xorg keymap layout ($xkblayout)"
		cat > /mnt/etc/X11/xorg.conf.d/00-keyboard.conf << END
Section "InputClass"
	Identifier "keyboard-all"
	Option "XkbLayout" "$xkblayout"
	MatchIsKeyboard "on"
EndSection
END
	fi
	if [ -d /mnt/etc/dconf ]; then
		echo "Setting up Gnome keymap layout ($xkblayout)"
		mkdir -p /mnt/etc/dconf/profile/
		cat > /mnt/etc/dconf/profile/user << EOF
user-db:user
system-db:local
EOF
		mkdir -p /mnt/etc/dconf/db/local.d/
		cat > /mnt/etc/dconf/db/local.d/00-keyboard << EOF
[org.gnome.desktop.input-sources]
sources=[('xkb', '$xkblayout')]
EOF
		chroot /mnt dconf update
	fi
fi

#chroot to live system
if [ -f /mnt/etc/slackware-version ]; then
	mount --move /dev /mnt/dev
	mount --move /proc /mnt/proc
	mount --move /sys /mnt/sys
fi
mount -o remount,ro /mnt
echo "*** Live system ready ***"
echo ""
exec switch_root /mnt /sbin/init
