#!/bin/bash
########################################################################
# MuGLIn - MuGLIn GNU/Linux Installation		                       #
#                                                                      #
# Copyright (C) 2010 Jakob Gurnhofer <jakob.gurnhofer@gmail.com>       #
# Copyricht (C) 2010 Srdjan Markovic <smark2ki@htl.moedling.at>        #
#                                                                      #
# This file is part of MuGLIn source code.                             #
#                                                                      #
# MuGLIn 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 3 of the License, or    #
# (at your option) any later version.                                  #
#                                                                      #
# MuGLIn 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 MuGLIn. If not, see <http://www.gnu.org/licenses/>.       #
########################################################################

. /etc/muglin/base.conf
. /etc/muglin/udpcast.conf

LOG="/var/log/muglin/installer"
PIPEDIR="/var/run/muglin/sessions/"

#we need to check if our file ends with tbz, so you need to provide a filename as $1.
# -> udpcast opts must not have an --file!

if [ "`echo $1 | egrep -v '.tgz$'`" != "" -a -e "$1" ]; then
	echo "ERROR: $1 is not a .tgz-File! Exiting!"
	exit -1
fi

image=$1
sid=$2
shift 2

case $1 in
#number of clients-autostart moved to own api-call, but $1=noc still kept checking
    noc|timeout)
    if [ "`echo $2 | grep -e '^[[:digit:]]*$'`" = "" ]; then echo "Autostart argument is missing or not numeric, aborting!"; exit -1; fi
    auto=$1
    auto_on=$2
    shift 2 ;;
    man) shift ;;
    *)
    echo "Invalid autostart condition, aborting!"
    exit -1;;
esac

if [ "`echo $1 | grep -e '^[[:digit:]]*$'`" = "" ]; then echo "Baseport is missing or not numeric, aborting!"; exit -1; fi
baseport=$1
shift

echo -e "\n\nStarting $sid with $image\n" >> $LOG
if ([ "`echo $@ | grep -v '\-\-file' | grep -v '\-\-nokbd' | grep -v '\-\-portbase' | grep -v '\-\-autostart'`" = "" ] && [ "`echo $@`" != "" ]);then
	echo "ERROR: --file, --portbase, --nokbd and --autostart is set by muglin, you must not provide them to udp-sender"
	exit -1
fi 
 
pipe=$PIPEDIR/$sid

if [ -p $pipe ]; then
	echo "Session already exists, aborting!"
	echo "exit -2" >> $LOG
	exit -2
fi
#Only we can say done, others need to cancel
AUTH=`pwgen -s 16 1`

mkfifo $pipe
#needed for internal communication(udp-sender's pid and return-code). wait didn't worked, and i had to implement it in some way, so its quite q&d
# -- srdja
mkfifo ${pipe}.int

pid=""

update_status(){
  echo "UPDATE Sessions SET State = $1 WHERE SID = '$sid'" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B
}

update_status 0;
noc=0;
autostart_tout(){
	sleep $1
	echo start > $pipe&
}

#autostart_noc(){
#	echo "Running in autostart_noc" >> $LOG
#	while true; do
#		sleep 3
#	done
#}

# i had to reimplement autostart_noc because it fucked me with a chainsaw (as the one guy in linux kernel's source said)
# so case left only for timeout again...
case "$auto" in
	timeout) autostart_tout $auto_on&;;
	#noc) autostart_noc $auto_on&;;
esac

run_udp_sender(){
	sudo udp-sender --file $image --interface $USE_IFACE --portbase $baseport --autostart 5 --nokbd $@ >/dev/null 2>&1 &
	pid=$!
	echo "${AUTH}pid" > $pipe
	sleep 0.1s
	echo "$pid" > ${pipe}.int
	wait $pid
	ret=$?
	echo "${AUTH}ret" > $pipe
	sleep 0.1s
	echo "$ret" > ${pipe}.int
}
finish=0
until [ "$finish" == "1" ]; do
	command=`cat $pipe`
	case $command in
		cancel)
			echo "cancel" >> $LOG
			#needs reimplementation, bacause killing $pid only kills transmit bot not udp-sender
			if [ "$pid" != "" ];then
				kill $pid;
			fi
			echo "DELETE FROM Sessions WHERE SID = '$sid'" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B
			finish=1
		;;
		start)
			if [ "$pid" != "" ];then
				echo "Session $sid already running" >> $LOG
				continue
			fi
			echo "start" >> $LOG
			update_status 1
			echo "UPDATE Clients SET Status = 20 WHERE SID = '$sid'" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B
			run_udp_sender&
		;;
		${AUTH}done)
			echo "done" >> $LOG &
			finish=1
		;;
		trigger)
			if [ "$auto" != "noc" ]; then continue; fi;
			noc=$(($noc+1))

			if [ "$noc" -ge "$auto_on" ]; then
				sleep 3
				echo "start" > $pipe &
				sleep 1
			fi
		;;
		${AUTH}pid)
			pid=$(cat ${pipe}.int)
		;;
		${AUTH}ret)
			ret=$(cat ${pipe}.int)
			if [ "$ret" == "0" ]; then	
				update_status 3
				mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B -e"UPDATE Clients SET Status = 21 WHERE SID = '$sid';"
			else
				update_status 2
				mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B -e"UPDATE Clients SET Status = -2 WHERE SID = '$sid';"
			fi
			finish=1
		;;
		*)
			echo "unknown cmd $command" >> $LOG
			echo "Unknown command in pipe, ignoring!"
		;;
	esac
done
echo "Leaving installer..." >> $LOG
rm $pipe*
