#!/bin/bash
#/etc/init.d/xbmc

. /lib/lsb/init-functions

get_opt() {
    echo "$@" | cut -d "=" -f 2
}

CMDLINE=$(cat /proc/cmdline)

#Process command line options
XBMC_PARAMS=""
for i in ${CMDLINE}; do
    case "${i}" in
	xbmc\=*)
		XBMC_PARAMS=$(get_opt $i)
		;;
	boot\=*)
		SRCMEDIA=$(echo "$i" | cut -d "=" -f 2)
		;;
    esac
done

XBMC_BOOTTORAM="$( echo $XBMC_PARAMS | grep "boottoram" )"

if [ "$XBMC_BOOTTORAM" != "" ]; then
        eject /dev/scd0 &> /dev/null
	eject /dev/scd1 &> /dev/null
	eject /dev/scd2 &> /dev/null
fi

case "$1" in
  start)
	log_action_begin_msg "Configuring system and starting XBMC"
	INSTALL="$( echo $XBMC_PARAMS | grep "install" )"
	if [ "$INSTALL" != "" ]; then
                # if usplash is runing, make sure to stop it now, yes "start" kills it.
                if pidof usplash > /dev/null; then
                        DO_NOT_SWITCH_VT=yes /etc/init.d/usplash start
                fi
	        su -c "/usr/bin/installXBMC.sh" -l 
	else
		RUNX="$(grep "splash" /proc/cmdline)"
		if [ "$RUNX" == "" ]; then
		        echo "Not starting X."
		else
			NOMOUNT="$( echo $XBMC_PARAMS | grep "nodiskmount" )"
			if [ "$NOMOUNT" = "" ]; then
				diskmounter &
			fi

			# Redirect XBMC home folder and logfile to usb flash
			if [ "$SRCMEDIA" = "usb" ]; then
				NOREDIR="$( echo $XBMC_PARAMS | grep "noredir" )"
				if [ "$NOREDIR" = "" ]; then
					echo "Redirect XBMC home folder and logfile to usb flash..."

					rootDrive=`pmount | grep mnt | cut -d " " -f 1`
					mount -t vfat -o rw,umask=000 $rootDrive /mnt

					# TODO change to /var/tmp when related bug closed
					touch /mnt/xbmc.log
					chmod 666 /mnt/xbmc.log
					if [ -f /xbmc.log ]; then
						rm /xbmc.log
					fi
					ln -s /mnt/xbmc.log /xbmc.log

					if [ ! -d /mnt/Userdata ]; then
						mkdir /mnt/dotXBMC
					fi

					if [ ! -L /home/xbmc/.xbmc ]; then
						mv /home/xbmc/.xbmc /home/xbmc/.xbmc.previous
						ln -s /mnt/dotXBMC /home/xbmc/.xbmc
					fi
				fi
			fi

			# if usplash is running, make sure to stop it now, yes "start" kills it.
			if pidof usplash > /dev/null; then
				DO_NOT_SWITCH_VT=yes /etc/init.d/usplash start
			fi
			runXBMC.sh &
		fi
	fi
	log_action_end_msg 0
	;;
  stop)
	killall Xorg xbmc
	;;

esac

exit 0

