#!/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 $FLIGHTGEARDIR = "/home/flightgear/local";
my $KILL_COMMAND = "killall fgms.conf";

my $Command = $ARGV[0];
if ($Command eq "")
{
	$Command = "NONE";
}

my $running=`ps ax|grep /home/flightgear/local/usr/sbin/fgms|grep -v grep`;

chdir ("$FLIGHTGEARDIR");

if ($Command eq "start")
{
	if ($running eq "")
	{
		print "Starting Flightgear...\n";
		if (-f "$FLIGHTGEARDIR/nostart")
		{
			print "Removing $FLIGHTGEARDIR/nostart\n";
			# Remove the lock file if it exists
			unlink("$FLIGHTGEARDIR/nostart");
		}
		chdir ("$FLIGHTGEARDIR");
		# Start the screen process
		system("nohup $FLIGHTGEARDIR/startflightgear > /tmp/FlightgearStartup.log\&");
	}
}
elsif ($Command eq "stop")
{
	print "Stopping Flightgear process...\n";
	system("touch '$FLIGHTGEARDIR/nostart'");
	if ($running ne "")
	{
		# Process is running, kill it
		system($KILL_COMMAND);
		sleep(10);
	}
}
elsif ($Command eq "restart")
{
	if (-f "$FLIGHTGEARDIR/nostart")
	{
		print("Removing $FLIGHTGEARDIR/nostart\n");
		unlink("$FLIGHTGEARDIR/nostart");
	}
	if ($running ne "")
	{
		system($KILL_COMMAND);
		sleep(10);
	}
}
elsif ($Command eq "status")
{
	if ($running ne "")
	{
		print("Flightgear Server Running\n");
	}
	else
	{
		print("Flightgear Server Not Running\n");
	}
}
else
{
	print ("Uknown command '$Command'\n");
	print ("Usage: $0 {start|status|stop|restart}\n");
	exit(1);
}

exit(0);
