#!/bin/ash

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

if cat /proc/cmdline | grep -q "quiet"; then quiet="quiet"; fi

source /etc/init.d/rcLive.inc
if [ -z "$quiet" ]; then echo -e "\n*** Live system initialization ***"; fi
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
			if [ -z "$quiet" ]; then echo "NFS: $livelabel:`dirname $livedir`"; fi
			mount -t nfs -o nolock $livelabel:`dirname $livedir` /live/media || mediadetected="error"
			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
			mediadetected="media"
			livedevice="/dev/$livedevice"
			if [ -z "$quiet" ]; then echo "$livelabel found on $livedevice"; fi
			mount $livedevice /live/media || mediadetected="error"
		else
			mdev -s
			sleep 1
			let sleeptime+=1
		fi
	done
fi
if [ "$mediadetected" = "none" ] || [ "$mediadetected" = "error" ]; 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"
			if [ -z "$quiet" ]; then echo "Loading SquashFS module $modulename"; fi
			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 #TODO / FIXME
END

tweak_system

#enable persistent connections
mkdir -p /mnt/etc/rc.d #Slackware / BSD style
cat > /mnt/etc/rc.d/rc.nm-connections << EOF
#!/bin/bash
mkdir -p /home/.cfg/nm-connections
case "\$1" in
"restore")
	cp /home/.cfg/nm-connections/* /etc/NetworkManager/system-connections/ 2>/dev/null
	chmod 600 /etc/NetworkManager/system-connections/* 2>/dev/null
	chown root:root /etc/NetworkManager/system-connections/* 2>/dev/null
	;;
"save")
	cp /etc/NetworkManager/system-connections/* /home/.cfg/nm-connections/ 2>/dev/null
	;;
esac
EOF
chmod +x /mnt/etc/rc.d/rc.nm-connections
enable_persistent_connections

#setup persistent homedir
if [ ! -z "$homelabel" ]; then
	homedevice=`blkid | grep "\"$homelabel\"" | sed -n 1p | cut -f1 -d:` #LABEL/UUID -> device
	if [ ! -z "$homedevice" ] && mount $homedevice /mnt/home; then
		echo "$homedevice /home auto defaults,noatime 0 0" >> /mnt/etc/fstab
	fi
elif [ "$mediadetected" = "media" ]; then
	mkdir -p /live/media/home 2>/dev/Null && #fails on read-only media
	mount --bind /live/media/home /mnt/home &&
	echo "/live/media/home /home none bind 0 0" >> /mnt/etc/fstab
else #NFS
	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
fi

#initialize homedirs
if mount | grep -q 'on /mnt/home'; then 
	sed -n '\@:/home/@p' /mnt/etc/passwd | sed -e /^ftp:/d -e /nologin$/d | while read passwd_entry; do
		passwd_uid_gid=$(echo $passwd_entry | cut -f3,4 -d:)
		passwd_home=$(echo $passwd_entry | cut -f6 -d:)
		if [ ! -d /mnt/$passwd_home ]; then
			if [ -z "$quiet" ]; then echo "Initializing $passwd_home directory"; fi
			cp -dpR /mnt/etc/skel /mnt/$passwd_home
			chown -R $passwd_uid_gid /mnt/$passwd_home
		fi
	done
fi

#rebind mounts
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
		if [ -z "$quiet" ]; then echo "Setting up Xorg keymap layout ($xkblayout)"; fi
		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
		if [ -z "$quiet" ]; then echo "Setting up Gnome keymap layout ($xkblayout)"; fi
		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
	if [ -d /mnt/etc/hypr ]; then
		if [ -z "$quiet" ]; then echo "Setting up Hyprland keymap layout ($xkblayout)"; fi
		echo -e "input {\n\tkb_layout = $xkblayout\n}" > /mnt/etc/hypr/keymap.conf
	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
if [ -z "$quiet" ]; then echo -e "*** Live system ready ***\n"; fi
exec switch_root /mnt /sbin/init
