#!/bin/busybox ash
# (c) Robert Shingledecker 2012
# Adjusted for dCore by Jason Williams 2014
# Load cde from iso file 
# At boot - called from tc-config with: iso=sdb1
# After boot in /opt/bootsync.sh with /usr/bin/fromISOfile sdb1
# After boot from command line with: sudo fromISOfile sdb1
. /etc/init.d/tc-functions
useBusybox
checkroot
[ -z "$1" ] && exit 1
read USER < /etc/sysconfig/tcuser || exit 1
[ -d /mnt/fromISOfile ] || mkdir /mnt/fromISOfile
TARGET="$1"
TARGET="${TARGET#/mnt/}"
TARGET="${TARGET#/dev/}"
DEVICE="${TARGET%%/*}"
if [ "${TARGET##*.}" == "iso" ]
then
	TARGET="${TARGET#*/}"
else
	TARGET=""
fi

find_mountpoint "$DEVICE"
if [ -z "$MOUNTPOINT" ]; then
	echo "Invalid device specified: $DEVICE"
	exit 1
fi
if ! mounted "$MOUNTPOINT"; then
	mount "$MOUNTPOINT"
	if [ "$?" != 0 ]; then
		echo "Unable to mount drive!"
		exit 1
	fi
fi
if [ -z "$TARGET" ]; then
	find "$MOUNTPOINT" -name "*.iso" > /tmp/isos.lst
	FOUND="$(awk '{print NR}' /tmp/isos.lst 2>/dev/null)" || FOUND=0
	if [ "$FOUND" == 0 ]; then
		echo "No iso file found on /mnt/$DEVICE"
		exit 1
	fi
	if [ "$FOUND" == 1 ]; then
		TARGET=$(cat /tmp/isos.lst)
	else
		echo "Multiple isos found, please use full path."
		cat /tmp/isos.lst
		exit 1
	fi
else
	TARGET="$MOUNTPOINT"/"$TARGET"
fi
echo "$TARGET"
mount -t iso9660 -o ro "$TARGET" /mnt/fromISOfile
if [ "$?" != 0 ]; then
	echo "Failed to mount specified $TARGET"
	exit 1
fi
if [ ! -d /mnt/fromISOfile/cde ]; then
	echo "no cde directory found in $TARGET"
	umount /mnt/fromISOfile
	exit 1
fi
echo "Loading SCE extensions from sceboot.lst of embedded cde directory."
CDELIST=/mnt/fromISOfile/cde/sceboot.lst
LOADFROM="/mnt/fromISOfile/cde/sce"
	while read FILE; do
		FILE=""$LOADFROM"/"$FILE".sce"
		BASENAME=`basename "$FILE"`
		APPNAME="${BASENAME%.sce}"
		if ! grep "$APPNAME" /tmp/.debinstalled > /dev/null 2>&1; then
			FLAGS=" -b "
			su "$USER" -c "sce-load $FLAGS $FILE"
			if [ -s /tmp/aberr ]; then
				echo "occured while loading: " "$FILE" >> /tmp/aberr
				umount /mnt/fromISOfile
				exit 1
			fi
		fi
	done < "$CDELIST"
	echo "$LOADFROM" > /etc/sysconfig/cde

# Wrap up by performing updates as may be needed.
if [ -e /etc/sysconfig/newmodules ]; then
	depmod -a 2>/dev/null
	/sbin/udevadm trigger
fi
/sbin/ldconfig 2>/dev/null
#setupHome
