#!/bin/sh
echo "**** ffp 0.5 usb-setup by wolf-u.li ****"
# Change Variables below here
USB_MOUNTP=/mnt/HD_a2/usbstorage
USB_DEV=sdb1
# Do not change anything below this line!
FFP_USB=$USB_MOUNTP/ffp

USBMODDIR=/mnt/HD_a2/.bootstrap
USBMOD=$USBMODDIR/usb-storage.ko

# Initialize variable
usbmod_loaded=no

# if the usb-module.ko does not exist, try to download it
if [ ! -e $USBMOD ]; then
	echo "Directory of usb-storage module not found. Will try to create directory for future actions."
	mkdir $USBMODDIR
	echo "usb-storage.ko module not found. Will try to to download it."
	wget -c http://wolf-u.li/download-manager.php?id=11 -O $USBMOD
fi

# Load & Copy usb-storage module
if [ -e $USBMOD ]; then
	echo "Found usb-storage.ko module."
	cp $USBMOD /lib/modules/
	#load usb-storage module
	insmod /lib/modules/usb-storage.ko
	echo "insmod usb-storage.ko"
	sleep 15
	usbmod_loaded=yes
else
	echo "usb-storage.ko module still not found. fun_plug won't run. Please contact wolf-u.li with this error"
fi

# Find the USB Device
if test $usbmod_loaded = yes; then
	usb_found=no
	grep $USB_DEV /proc/partitions >/dev/null 2>/dev/null
	if [ $? -ne 0 ]; then
		# wait for disk...
		let timeout=30
		echo "Waiting for $USB_DEV (up to $timeout seconds) ..."
		while [ $timeout -gt 0 ]; do
			grep $USB_DEV /proc/partitions >/dev/null 2>/dev/null
			[ $? -eq 0 ] && break
			sleep 3
			let timeout=${timeout}-5
		done
		grep $USB_DEV /proc/partitions >/dev/null 2>/dev/null
		if [ $? -ne 0 ]; then
			echo "Failed. Did not find $USB_DEV in /proc/partitions."
			usb_found=no
		else
			echo "Found $USB_DEV in /proc/partitions"
			usb_found=yes
		fi
	else
		usb_found=yes
	fi

	# Mount the USB-Device
	if test $usb_found = yes; then
		mkdir -p $USB_MOUNTP
		echo -n "Mounting /dev/$USB_DEV on $USB_MOUNTP ..."
		mount /dev/$USB_DEV $USB_MOUNTP -o noatime
		if [ $? -ne 0 ]; then
			echo "Failed"
		else
			echo "Success"
		fi
	fi
else
	echo "usb-storage.ko module not loaded."
fi

# Check if Directory of ffp exists on the USB-Device and check if it is already installed (fun_plug.tgz doesn't exist, if it's installed).
if [ -d $FFP_USB ] || [ -r $USB_MOUNTP/fun_plug.tgz ]; then
	echo "* Found FFP on USB device"
	FFP_PATH=$FFP_USB
	FFP_TARBALL=$USB_MOUNTP/fun_plug.tgz
else
	echo "* FFP was not found on a USB device. Will try to download it."
	# Get the present Link for ffp 0.5
	wget http://wolf-u.li/download-manager.php?id=17 -O $USB_MOUNTP/ffp-link.txt
	# Remove a old fun_plug.tgz to ensure the newest version
	rm $USB_MOUNTP/fun_plug.tgz
	# Download the Link
	wget -O $USB_MOUNTP/fun_plug.tgz -i $USB_MOUNTP/ffp-link.txt
	# DEBUGGING: ls -al $USB_MOUNTP
	# Remove the temporary Linkfile
	rm $USB_MOUNTP/ffp-link.txt
	# Check if it now exists
	if [ -r $USB_MOUNTP/fun_plug.tgz ]; then
		echo "* FFP was downloaded to the USB device."
		FFP_PATH=$FFP_USB
		FFP_TARBALL=$USB_MOUNTP/fun_plug.tgz
	else
		echo "Probably no Internet Connection or any other Problem, reverting back to HDD...."
	fi
fi