#!/bin/bash

#      Copyright (C) 2005-2008 Team XBMC
#      http://www.xbmc.org
#
#  This Program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2, or (at your option)
#  any later version.
#
#  This Program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with XBMC; see the file COPYING.  If not, write to
#  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#  http://www.gnu.org/copyleft/gpl.html


if [ "$(pidof xbmc.bin)" ] ; then
	exit
fi

if [ "$(pidof X)" ] ; then
	/usr/bin/xbmc --standalone
	exit
fi

while true
do
	if [ "$(whoami)" == "root" ] ; then
		xbmcUser=xbmc

		# Read configuration variable file if it is present
		[ -r /etc/default/xbmc-live ] && . /etc/default/xbmc-live

		if ! getent passwd $xbmcUser >/dev/null; then
			xbmcUser=$(getent passwd 1000 | sed -e 's/\:.*//')
			if [ -z "$xbmcUser" ]; then
				echo "User for XBMC not found, exiting..."
				break
			fi
		fi
	else
		xbmcUser=$(whoami)
	fi

	echo "#!/bin/bash" >  /home/$xbmcUser/.xsession
	echo "/usr/bin/xbmc --standalone" >>  /home/$xbmcUser/.xsession

	echo "case \"\$?\" in" >>  /home/$xbmcUser/.xsession
	echo "    0 ) # Quit" >>  /home/$xbmcUser/.xsession
	echo "        touch /tmp/noRestartXBMC" >> /home/$xbmcUser/.xsession
	echo "        break ;;"  >>  /home/$xbmcUser/.xsession
	echo "    64 ) # Shutdown System"  >>  /home/$xbmcUser/.xsession
	echo "        sleep 10 ;;"  >>  /home/$xbmcUser/.xsession
	echo "    65 ) # Warm Reboot"  >>  /home/$xbmcUser/.xsession
	echo "        echo "Restarting XBMC ..." ;;"  >>  /home/$xbmcUser/.xsession
	echo "    66 ) # Reboot System"  >>  /home/$xbmcUser/.xsession
	echo "        sleep 10 ;;"  >>  /home/$xbmcUser/.xsession
	echo "     * ) ;;"  >>  /home/$xbmcUser/.xsession
	echo "esac"  >>  /home/$xbmcUser/.xsession

	chown $xbmcUser:$xbmcUser /home/$xbmcUser/.xsession

	initctl emit starting-x

	if [ "$(whoami)" == "root" ] ; then
		su $xbmcUser -c "startx -- -br > /dev/null 2>&1"
	else
		startx -- -br > /dev/null 2>&1
	fi

	if [ -e /tmp/noRestartXBMC ] ; then
		rm /tmp/noRestartXBMC
		rm /home/$xbmcUser/.xsession
		break
	fi

#	sleep 2
done
