#!/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

NAME=""
SID=""

. /usr/local/lib/muglin/muglin.d/libmuglin

# s start
# t status
# r create
# c cancel
# d sid
# n name
# i image
# o starton
# t timeout
# m numofclients

while getopts stcr:d:n:i:o:t:m: OPTION;do
	case "$OPTION" in
		# lvl1 cmds
		s) setcmd start;;
		t) setcmd status;;
		r)
			setcmd create
			if [ "`echo $OPTARG | egrep '^\-'`" != "" ]; then echo "Session name must not start with \"-\" (maybe missing argument?), aborting!"; exit -1; fi
			SESSIONNAME=$OPTARG
		;;
		c) setcmd cancel;;
		h)
		cat << HELP
Options:
-s 		  Start
-c		  Cancel
-t 		  Show status
Supported suboptions:
  -d <SID>	  SID of session
  -n <Name>	  Name of session
At least one of them is required.

Or
-r <Name>	  Create new session
Suboptions:
  -i <Image-Name> Name of image to install
  -o <Type>	  Start-On option. Supported types: manual, numberofclients and timeout (self explaining)
If "-o timeout":
  -t <Number>	  Timeout to start the transmission (in seconds)
If "-o numofclients":
  -m <Number>	  Number of clients to connect, before starting transmission

HELP
		# lvl2 cmds
		# start / cancel
		d)
			if [ "$CMD" = "create" ]; then echo "--sid is not a valid option for -create. Aborting"; exit -1; fi
			if [ "`echo $OPTARG | grep -e '^[[:digit:]]*$'`" = "" ]; then echo "Argument for --sid is missing or not numeric, aborting!"; exit -1; fi
			if [ "$SID" = "" -a "$NAME" = "" ]; then
				SID=$OPTARG
			else
				echo "--sid or --name already provided, aborting!"
				exit -1;
			fi				
		;;
		n)
			if [ "$CMD" = "create" ]; then echo "--name is not a valid option for -create. Aborting"; exit -1; fi 
			if [ "`echo $OPTARG | egrep '^\-'`" != "" ]; then echo "Session name must not start with \"-\" (maybe missing argument?), aborting!"; exit -1; fi
			if [ "$SID" = "" -a "$NAME" = "" ]; then
				NAME="$OPTARG"
			else
				echo "--sid or --name already provided, aborting!"
				exit -1;
			fi
		;;
		
		# create
		i)
			# our image param is not a file
			# if [ -f $1 ]; then echo "File \"$1\" not found, aborting!"; exit -1; fi

			if [ "$CMD" != "create" ]; then echo "--image is only valid for -create. Aborting"; exit -1; fi
			checkimagename "$OPTARG"
			IMAGE=$OPTARG
		;;
		o)
			if [ "$CMD" != "create" ]; then echo "--starton only valid for -create. Aborting"; exit -1; fi

			case $OPTARG in
				timeout) STARTON=timeout;;
				numofclients) STARTON=noc;;
				manual) STARTON=man;;
				*) echo "Unknown argument \"$1\", aborting!"; exit -1;;
			esac
			
		;;
		t)
			if [ $STARTON != timeout ]; then echo "---timeout is only valid for --starton timeout. Aborting"; exit -1; fi
t
			if [ "`echo $OPTARG | grep -e '^[[:digit:]]*$'`" = "" ]; then echo "Argument for ---timeout is missing or not numeric, aborting!"; exit -1; fi
			STARTCNT=$OPTARG
		;;
		m)
			if [ $STARTON != noc ]; then echo "---numofclients is only valid for --starton numofclients. Aborting"; exit -1; fi

			if [ "`echo $OPTARG | grep -e '^[[:digit:]]*$'`" = "" ]; then echo "Argument for ---numofclients is missing or not numeric, aborting!"; exit -1; fi
			STARTCNT=$OPTARG
		;;

		\?)
		  echo "Unknown option \"-$1\". Aborting"
		  exit -1
		;;
		:)
		  echo "Option \"-$OPTARG\" requires an argument. Aborting."
		  exit -1
		;;
	esac
done
case $CMD in
	start)
		if [ "$SID" = "" ]; then
			SID=`mysql -u $MYS_USER -p$MYS_PASS -D$MYS_DB  --skip-column-names -e"SELECT SID FROM Sessions WHERE Name = '$NAME';"`
			if [ "$SID" = "" ]; then echo "No session named \"$NAME\", leaving"; exit -2; fi
		fi
		echo start > /var/run/muglin/sessions/$SID
	;;
	create)
		# TODO: I should move this code to installer, because the installer "is" a session
		session=`echo "SELECT Name FROM Sessions WHERE NAME = '$SESSIONNAME'" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB --skip-column-names -B`
		if [ "$session" != "" ]; then
			echo "Session \"$SESSIONNAME\" already exists. Aborting!"
			exit -6
		fi
		answer=`echo "SELECT IID,Path FROM Images WHERE Name = '$IMAGE'" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB --skip-column-names -B`
		i=0
		# now we put IID in results[0] and Path in results[1], this is the simpliest way to parse an sql answer
		for result in $answer;do
			results[$i]=$result;
			i=$(($i+1))
		done

		if [ "${results[0]}" = "" ]; then
			echo "No IID for \"$IMAGE\" found. Aborting!"
			exit -4
		fi
		i=0
		# i've tried to fix bug #2952057, but it needs to be tested.
		basep_result=`echo "SELECT Value FROM Config WHERE Var = 'UDP_BASEP_START' OR Var = 'UDP_BASEP_NEXT' OR Var = 'UDP_BASEP_END' ORDER BY Var DESC" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB --skip-column-names -B`
		for result in $basep_result; do
			# 0: start, 1: next, 2: end
			basep[$i]=$result;
			i=$(($i+1))
		done
		basep_next=$((${basep[1]}+1))
		if [ "$basep_next" -le "${basep[2]}" ]; then
			echo "UPDATE Config SET Value = $basep_next WHERE Var = 'UDP_BASEP_NEXT'" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB --skip-column-names -B
		else
			echo "UPDATE Config SET Value = ${basep[0]} WHERE Var = 'UDP_BASEP_NEXT'" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB --skip-column-names -B
		fi
		BASEPORT=$((${basep[1]}*2))
		
		echo "INSERT INTO Sessions (IID,Name,State,Baseport) VALUES (${results[0]},'$SESSIONNAME',0,$BASEPORT)" | mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB  --skip-column-names -B
		SID=`echo "SELECT SID FROM Sessions WHERE Name = '$SESSIONNAME'"| mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB  --skip-column-names -B`
		/usr/local/lib/muglin/installer ${results[1]}/image.tgz $SID $STARTON $STARTCNT $BASEPORT&
		
	;;
	cancel)
		if [ "$SID" = "" ]; then
			SID=`mysql -u $MYS_USER -p$MYS_PASS -D$MYS_DB  --skip-column-names -e"SELECT SID FROM Sessions WHERE Name = '$NAME';"`
			if [ $SID = "" ]; then echo "No session named \"$NAME\", leaving"; exit -2; fi
		fi
		echo "SID: $SID"
		pipe=/var/run/muglin/sessions/$SID
		if [ -p $pipe ]; then
			echo cancel > $pipe
		else
			echo "ERROR: Missing command pipe for SID: \"$SID\". Deleting entry from DB"
			mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B -e"DELETE FROM Sessions WHERE SID = '$SID';" > /dev/null 2>&1
		fi
	;;
	status)
		SESSIONS=($(mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B --skip-column-names -e"SELECT SID,Name,State FROM Sessions;"));
		sCOUNT=$(echo SESSIONS | wc -w)
		for((i=0;i<sCOUNT;i=i+3)); do
			cCOUNT=$(mysql -u$MYS_USER -p$MYS_PASS -D$MYS_DB -B --skip-column-names -e"SELECT COUNT(*) FROM Clients WHERE SID = ${SESSIONS[$i]}")
			echo -n "${SESSIONS[$i+1]} (SID: ${SESSIONS[$i]}): "
			case ${SESSIONS[i+2]} in
			    0) echo -n "waiting";;
			    1) echo -n "running";;
			    2) echo -n "finished";;
			    3) echo -n "error (see log)";;
			    *) echo -n "unknown";;
			esac
			echo " with $cCOUNT Client(s) connected."
		done
	;;
esac
			
