#!/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 $OPENRCT2DIR = "/home/openrct-user/OpenRCT2";
my $SCREENCMD = "/usr/bin/screen";

# No changes below here...

my $exists = "";

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

my $running=`ps ax|grep openrct2-server|grep -v grep`;

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

while (-1)
{
	chdir $OPENRCT2DIR;
	# check if OpenRCT2 process is running
	$running=`ps ax|grep openrct2-server|grep -v grep`;
	if ($running eq "")
	{
		print "OpenRCT2 not running\n";
		# See if they want the server started
		if (! -f "$OPENRCT2DIR/nostart")
		{
			# The Log Entry
			my $datestring = localtime();
			my $TIME="OpenRCT2 Down, Restarting: $datestring";
			open(OUTF, ">>$OPENRCT2DIR/OpenRCT2Screen.log") || die "Unable to open $OPENRCT2DIR/OpenRCT2Screen.log for appending";
			print (OUTF "$TIME\n");
			close($OUTF);
			chdir "$OPENRCT2DIR";
			print "Starting screen process\n";
			system("$SCREENCMD -fa -S OpenRCT2 -d -U -m $OPENRCT2DIR/bin/openrct2-server host MySaveGame.park --port 11753");
		}
	}
	# Sleep for 1 minutes before checking again
	sleep(60);
}
exit(0);
