#!/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 $SBBSDIR = "/sbbs";
my $SCREENCMD = "/usr/bin/screen";

# No changes below here...

my $startpath = $ENV{'PATH'};
my $newpath = "$SBBSDIR/exec:$startpath";
my $exists = "";
my $PidFile = "/sbbs/ctrl/sbbs.pid";

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

sub IsRunning
{
	if (! -f $PidFile)
	{
		print "PID file not found\n";
		return("nope");
	}
	# PID file found, checking for process
	open(my $fh, '<:encoding(UTF-8)', $PidFile);
	if ($fh eq "")
	{
		print "Could not open file '$PidFile' for reading $!";
		return("nope");
	}
	my $CurLine = 0;
	while (my $row = <$fh>)
	{
		chomp $row;
		print "Read pid file '$row'\n";
		$CurLine = $row;
	}
	close($fh);
	if (kill(0, $CurLine) != 1)
	{
		return "nope";
	}
	return "sbbs";
}

my $running=IsRunning();

# check if BBS process is running
if ($running eq "sbbs")
{
	print ("Startupscript already running...\n");
	exit (0);
}

while (-1)
{
	chdir $SBBSDIR;
	$running=IsRunning();

	# check if BBS process is running
	if ($running ne "sbbs")
	{
		print "SBBS not running - waiting to check:\n";
		sleep(10);
		my $running2=IsRunning();
		if ($running2 eq "sbbs")
		{
			print "Was running again\n";
			next;
		}

		print "Was still not running, checking for restart\n";
		# See if they want the server started
		if (! -f "$SBBSDIR/nostart")
		{
			# The Log Entry
			my $datestring = localtime();
			my $TIME="SBBS Down, Restarting: $datestring";
			open(OUTF, ">>$SBBSDIR/SBBSScreen.log") || die "Unable to open $SBBSDIR/SBBSScreen.log for appending";
			print (OUTF "$TIME\n");
			close($OUTF);
			chdir $SBBSDIR;
			print "Starting screen process\n";
			system("$SCREENCMD -fa -S SBBS -d -U -m sbbs");
		}
	}
	# Sleep for 1 minute before checking again
	sleep(60);
}
exit(0);
