#!/usr/bin/perl

# 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 1, 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 this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

my $OPENSIMDIR = "/home/osowner/opensim";
my $SCREENCMD = "/usr/bin/screen";

# No changes below here...

my $startpath = $ENV{'PATH'};
my $newpath = "$OPENSIMDIR/exec:$startpath";
my $exists = "";

# Set ENV vars
$ENV{'PATH'} = $newpath;
$ENV{'TERM'} = "xterm-256color";

my $running=`ps ax|grep OpenSim.exe|grep -v grep`;

# check if Opensim process is running
if ($running ne "")
{
	print ("Opensim Startup script already running...\n");
	exit (0);
}

while (-1)
{
	chdir $OPENSIMDIR;
	# check if Opensim process is running
	$running=`ps ax|grep OpenSim.exe|grep -v grep`;
	if ($running eq "")
	{
		print "Opensim not running\n";
		# See if they want the server started
		if (! -f "$OPENSIMDIR/nostart")
		{
			# The Log Entry
			my $datestring = localtime();
			my $TIME="Opensim Down, Restarting: $datestring";
			open(OUTF, ">>$OPENSIMDIR/OpensimScreen.log") || die "Unable to open $OPENSIMDIR/OpensimScreen.log for appending";
			print (OUTF "$TIME\n");
			close($OUTF);
			chdir "$OPENSIMDIR/bin";
			print "Starting screen process\n";
			system("$SCREENCMD -fa -S Opensim -d -U -m ~/opensim/bin/opensim.sh");
		}
	}
	# Sleep for 5 minutes before checking again
	sleep(300);
}
exit(0);
