#!/usr/bin/perl
use strict;
use warnings;

use UI::Dialog;
use Term::ReadKey;
use Term::ANSIScreen qw(cls);

my $FileEditor = "/bin/nano";
my $InitDName = "/etc/init.d/alienarena";
my $ALIENARENADIR = "/home/aaowner/alienarena";
my $BackupCommand = "/home/aaowner/AlienArenaBackup/alienarenabackup.pl";
my $PagerCommand = "/usr/bin/less";
my $MapsLst = "/home/aaowner/alienarena/arena/maps.lst";
my $DefaultCfg = "/home/aaowner/alienarena/arena/default.cfg";
my $ServerCfg = "/home/aaowner/alienarena/arena/server.cfg";
my $MOTD = "/home/aaowner/alienarena/arena/motd.txt";

###################################################
# No changes below here
###################################################

my $MySettings = "$ENV{'HOME'}/.aamcrc";

my $AAMC_ver = "1.4";
my $Record = "false";	# Are results saved?
my $TempDir = "/tmp";
my $RobotName = "";
my $BotVersion = "";
my $UserName = "";
my $ServerStatus = "foo";

my $d = new UI::Dialog ( backtitle => "Alien Arena Management Console v$AAMC_ver", height => 20, width => 65, listheight => 5,
	order => [ 'ascii', 'cdialog', 'xdialog' ]);

my $windowtitle = "Welcome to the Alien Arena Management Console!";
my $enjoyedtitle = "We hope you enjoyed AAMC!";
my $introtext =
"This is the Alien Arena Management Console, a utility for Alien Arena operators
to manage their servers from a text GUI rather than the command line.";

$d->msgbox( title => $windowtitle, text => $introtext );

if (($d->state() eq "ESC") || ($d->state() eq "CANCEL"))
{
	exit 0;
}

# Check for config file
if (-f $MySettings)
{
	# Read in settings
	open (my $FH, "<", $MySettings) or die "Could not read default file '$MySettings' $!";
	while (<$FH>)
	{
		chop();
		my ($Command, $Setting) = split(/=/, $_);
		if ($Command eq "fileeditor")
		{
			$FileEditor = $Setting;
		}
		if ($Command eq "initdname")
		{
			$InitDName = $Setting;
		}
		if ($Command eq "alienarenadir")
		{
			$ALIENARENADIR = $Setting;
		}
		if ($Command eq "backupcommand")
		{
			$BackupCommand = $Setting;
		}
		if ($Command eq "pagercommand")
		{
			$PagerCommand = $Setting;
		}
		if ($Command eq "mapslist")
		{
			$MapsLst = $Setting;
		}
		if ($Command eq "servercfg")
		{
			$ServerCfg = $Setting;
		}
		if ($Command eq "defaultcfg")
		{
			$DefaultCfg = $Setting;
		}
		if ($Command eq "motd")
		{
			$MOTD = $Setting;
		}
	}
	close($FH);
}
else
{
	# Store defaults
	open (my $FH, ">", $MySettings) or die "Could not create default file '$MySettings' $!";
	print $FH "fileeditor=/bin/nano\n";
	print $FH "initdname=/etc/init.d/alienarena\n";
	print $FH "alienarenadir=/home/aaowner/alienarena\n";
	print $FH "backupcommand=/home/aaowner/AlienArenaBackup/alienarenabackup.pl\n";
	print $FH "pagercommand=/usr/bin/less\n";
	print $FH "defaultcfg=/home/aaowner/alienarena/arena/default.cfg\n";
	print $FH "mapslst=/home/aaowner/alienarena/arena/default.cfg\n";
	print $FH "motd=/home/aaowner/alienarena/arena/motd.txt\n";
	print $FH "servercfg=/home/aaowner/alienarena/arena/server.cfg\n";
	close($FH);
}

my $menuselection = "";


sub CheckServerStatus
{
	my $running=`ps ax|grep alienarena-linux64-dedicated|grep -v grep`;
	if ($running ne "")
	{
		$ServerStatus = "Running";
	}
	else
	{
		$ServerStatus = "Stopped";
	}

}

sub MainMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$ALIENARENADIR/nostart")
	{
		$WantRespawn="OFF";
	}

	$menuselection = $d->menu( title => "Main Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Start Server',
                                      '2', 'Stop Server',
                                      '3', 'Server Console',
                                      '4', 'Turn Off Respawn',
                                      '5', 'Turn Respawn On',
                                      '6', 'Edit default.cfg',
                                      '7', 'Edit maps.lst',
                                      '8', 'Edit server.cfg',
                                      '9', 'Edit motd.txt',
                                      '10', 'Run Backup',
                                      '11', 'Edit Settings',
                                      '12', 'Restart Game',
                                      'q', 'Quit AAMC' ] );
}

while (-1)
{
	MainMenu();
	if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
	{
		$d->msgbox( title => $enjoyedtitle, text => "Thanks for using AAMC..." );
		exit 0;
	}
	if ($menuselection eq "1")
	{
		system("$InitDName start");
	}
	elsif ($menuselection eq "2")
	{
		if ($d->yesno( text => "Confirm stopping the server", text => "Are you sure you want to shut down the server?" ))
		{
			system("$InitDName stop");
			sleep(5);
			system("killall alienarena-linux64-dedicated");
		}
	}
	elsif ($menuselection eq "3")
	{
		$d->msgbox( text => "To exit the Alien Arena console and return to AAMC press CTRL-A CTRL-D" );
		system("screen -r AlienArena");
	}
	elsif ($menuselection eq "4")
	{
		# Turn off respawn
		system("touch $ALIENARENADIR/nostart");
	}
	elsif ($menuselection eq "5")
	{
		# Turn respawn back on
		if (-f "$ALIENARENADIR/nostart")
		{
			unlink("$ALIENARENADIR/nostart");
		}
	}
	elsif ($menuselection eq "6")
	{
		# Edit default.cfg file
		system("$FileEditor $DefaultCfg");
	}
	elsif ($menuselection eq "7")
	{
		# Edit maps.lst file
		system("$FileEditor $MapsLst");
	}
	elsif ($menuselection eq "8")
	{
		# Edit server.cfg file
		system("$FileEditor $ServerCfg");
	}
	elsif ($menuselection eq "9")
	{
		# Edit motd.txt file
		system("$FileEditor $MOTD");
	}
	elsif ($menuselection eq "10")
	{
		# Run a backup
		system("clear");
		system("$BackupCommand");
		print "Press Enter To Continue";
		my $entered = <STDIN>;
	}
	elsif ($menuselection eq "11")
	{
		# Edit settings file
		system("$FileEditor $MySettings");
	}
	elsif ($menuselection eq "12")
	{
		# Reset server process
		print "Killing Alien Arena Server Process\n";
		system("killall alienarena-linux64-dedicated");
		print "Process killed...";
		sleep(5);
	}
}

exit 0;
