#!/bin/bash

source common.sh
getPrgDir

USER=$(whoami)
console_name="SledjChisl"
tmux_command="tmux -S ${PRGDIR}/../../var/run/opensim-tmux.socket"
tmux_session=${console_name}
tmux_window="${tmux_command} select-window -t ${tmux_session}"
tmux_send="${tmux_command} send-keys -t ${tmux_session}"
bindir="${PRGDIR}/../bin"
date=$(date '+%F_%T')
all=""
delay=45
quiet=""
waiting=""
inventory=""

function wait_for_text()
{
    while :; do
	sleep 10
	${tmux_command} capture-pane -t ${tmux_session}:"${1}" -p | grep -E "${2}" 2>&1 > /dev/null && return
    done
}


if [ $USER = "${OS_USER}" ]
then
    SUDO=""
else
    SUDO="sudo -Hu ${OS_USER}"
fi

if [ "$1" = "-a" ]
then
    all="-a"
    shift 1
fi

if [ "$1" = "-d" ]
then
    delay=$2
    shift 2
fi

if [ "$1" = "-q" ]
then
    quiet="-q"
    shift 1
fi

if [ "$1" = "-w" ]
then
    waiting="-w"
    shift 1
fi

if [ "x$1" = "x" ]; then
    tgt=$(basename $(pwd))
    # These checks are kludgy.
    if [ "$tgt" = "scripts" ]; then
	all="-a"
	cd ${PRGDIR}/../../config/ROBUST
	tgt="ROBUST"
    fi
    if [ "$tgt" = "bin" ]; then
	uptime
	wait_for_text "ROBUST" "INITIALIZATION COMPLETE FOR ROBUST"
	if [ ! "x$all" = "x" ]
	then
	    echo "Sleeping for $((${delay} / 2)) seconds."
	    sleep $((${delay} / 2))
	    for i in $(seq -w 1 99)
	    do
		if [ -e "${PRGDIR}/../../config/sim${i}" ]
		then
		    uptime
		    echo "Starting sim${i}."
		    cd ${PRGDIR}/../../config/sim${i}; ./start-sim -w
		    uptime
		    # Sleep for a while, so that there is plenty of time to finish starting scripts and such,
		    # and we are not keeping the computer very busy if there are lots of sims.
		    echo "Sleeping for ${delay} seconds."
		    sleep ${delay}
		fi
	    done
	    uptime
	fi
	exit 0
    fi
    num="$(echo ${tgt} | cut -c 4-)"
elif [ -d "$1" ]; then
    tgt=$1
elif [ -d "sim$1" ]; then
    num=$1
    tgt="sim${num}"
else
    tgt=$1
    inventory=$1
fi

if [ "x$tgt" = "x" ]; then
    echo "usage:"
    echo "    $ $(basename $0) <sim>"
    echo "where <sim> is one of: " robust sim[0-9][0-9]
    exit 1
fi

cd ${bindir}

if ( ${tmux_command} -q list-sessions 2>/dev/null | grep -q ${console_name}: ); then
    true
else
    # The sudo is only so that the session is owned by opensim, otherwise it's owned by whoever ran this script, which is a likely security hole.
    # After the session is created, we rely on the ${PRGDIR}/../../caches/ directory to be group sticky, so that anyone in the opensim group can attach to the tmux socket.
    $SUDO ${tmux_command} new-session -d -s ${console_name} -n "ROBUST"
fi


if [ "x$tgt" = "xROBUST" ]; then
    exe="Robust"
    title="ROBUST"
elif [ "x$inventory" = "x" ]; then
    exe="OpenSim"
    # Grab the first RegionName line of the sims .ini file, cut it down to the name.
    title=$(getSimName ${num})
fi

case $(basename $0) in 
    "start-sim")
	cmd="mono ${exe}.exe -inidirectory=../../config/${tgt} "

	# Check if it's already running.
	if [ -e ${PRGDIR}/../../caches/${tgt}.pid ]
	then
	    # Double check if it's REALLY running.
	    if [ "x$(ps -p $(cat ${PRGDIR}/../../caches/${tgt}.pid) --no-headers -o comm)" = "x" ]; then
		$SUDO rm -f  ${PRGDIR}/../../caches/${tgt}.pid
	    fi
	fi
	# Now see if it's really really running.  lol
	if [ ! -e ${PRGDIR}/../../caches/${tgt}.pid ]
	then
	    if [ "x$tgt" = "xROBUST" ]; then
		${tmux_command} split-window -hp 50 -t "${tmux_session}:" "${cmd}"
	    else
		${tmux_command} new-window -dn "${title}" -t "${tmux_session}:${num}" "${cmd}"
	    fi
	fi

	if [ ! "x$all" = "x" ]
	then
	    ${tmux_send}:ROBUST.{left} "../scripts/start-sim -a -d ${delay}" Enter
	fi

	if [ "x$quiet" = "x" ]
	then
	    if [ "x$tgt" = "xROBUST" ]; then
		${tmux_window} \; attach-session -t "${tmux_session}"
	    fi
	fi

	if [ ! "x$waiting" = "x" ]
	then
	    wait_for_text "${title}" "INITIALIZATION COMPLETE FOR ${title}"
	fi
	;;

    "backup-inventory")
	cd ${PRGDIR}
	$SUDO ${PRGDIR}/gitAR.sh i "${inventory}"
	user=$(sanitize "${inventory}")
	# Add the full date and time to create the IAR file name.
	cmd="save iar -c ${inventory} / password ${PRGDIR}/../../backups/${user}-${date}.iar"
	# Do it in the highest numbered window.
	${tmux_send}:"$" "${cmd}" Enter
	wait_for_text "$" "Saved archive with [[:digit:]]+ items for ${user/_/ }"
	${tmux_send}:"$" "force gc" Enter Enter Enter
	;;

    "backup-sim")
	if [ -e ${PRGDIR}/../../caches/${tgt}.pid ]; then
	    cd ${PRGDIR}
	    $SUDO ${PRGDIR}/gitAR.sh o "${title}"
	    sim=$(sanitize "${title}")
	    # Add the full date and time to create the OAR file name.
	    cmd="save oar --all ${PRGDIR}/../../backups/${sim}-${date}.oar"
	    ${tmux_send}:"${title}" "${cmd}" Enter
	    wait_for_text "${title}" "Finished writing out OAR for ${title}"
	    # Generate the map tiles, coz the good generator leaks memory badly if you leave it turned on.
	    ${tmux_send}:"${title}" "generate map" Enter
	    ${tmux_send}:"${title}" "force gc" Enter Enter Enter
	else
	    echo "No OAR created for ${title}, it's not running."
	fi
	;;

    "stop-sim")
	if [ -e ${PRGDIR}/../../caches/${tgt}.pid ]; then
	    ${tmux_send}:"${title}" "alert WARNING - Emergency shutdown in one minute!" Enter
	    ${tmux_send}:"${title}" "alert WARNING - Emergency shutdown in one minute!" Enter
	    sleep 30
	    ${tmux_send}:"${title}" "alert WARNING - Emergency shutdown in thirty seconds!" Enter
	    ${tmux_send}:"${title}" "alert WARNING - Emergency shutdown in thirty seconds!" Enter
	    sleep 30
	    ${tmux_send}:"${title}" "shutdown" Enter
	    sleep 30
	    if [ -e ${PRGDIR}/../../caches/${tgt}.pid ]; then
		echo "Killing it with extreme prejudice!"
		kill -TERM `cat ${PRGDIR}/../../caches/${tgt}.pid`
	    fi
	else
	    echo "Sim ${title} is not running, so not stopping."
	fi
	;;
esac