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

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

my $FileEditor = "/bin/nano";
my $StartScript = "/home/stkowner/bin/supertuxkart";
my $SUPERTUXKARTDIR = "/home/stkowner/install";
my $BackupCommand = "/home/stkowner/SuperTuxKart_Backup/stkbackup.pl";
my $STKLog = "SUPERTUXKARTDIR/SuperTuxKartScreen.log";
my $Pager = "/usr/bin/less";
my $STKMCDir = "/home/stkowner/SuperTuxKart_Management";
my $BackupToolDir = "/home/stkowner/SuperTuxKart_Backup";
my $StartupDir = "/home/stkowner/SuperTuxKartStartup";
my $UpdateCommand = "/usr/bin/git pull";
my $BinDir = "/home/stkowner/bin";
my $DEBUG_MODE = "off";

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

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

sub PrintDebugCommand
{
	if ($DEBUG_MODE eq "off")
	{
		return;
	}
	my $PassedString = shift;
	print "About to run:\n$PassedString\n";
	print "Press Enter To Run This:";
	my $entered = <STDIN>;
}

my $d = new UI::Dialog ( backtitle => "Super Tux Kart Server Management Console v$STKMC_ver", height => 20, width => 65, listheight => 5,
	order => [ 'ascii', 'cdialog', 'xdialog' ]);

my $windowtitle = "Welcome to the Super Tux Kart Server Management Console!";
my $enjoyedtitle = "We hope you enjoyed STKMC!";
my $introtext =
"This is the Super Tux Kart Server Management Console, a utility for
Super Tux Kart Server 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;
}

my $menuselection = "";

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

}

sub DoUpdate
{
	my $DesiredDir = $_[0];

	# Update desired utility
	chdir ($DesiredDir);
	PrintDebugCommand("Running $UpdateCommand in $DesiredDir\n");
	system("$UpdateCommand");
	print "Press Enter To Continue";
	my $entered = <STDIN>;
}

sub UpdateToolsMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$SUPERTUXKARTDIR/nostart")
	{
		$WantRespawn="OFF";
	}
	$menuselection = $d->menu( title => "Update Tools Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Update STKMC',
                                      '2', 'Update Backup',
                                      '3', 'Update Startup',
                                      'q', 'Main Menu' ] );
}

sub UpdateTools
{
	while (-1)
	{
		UpdateToolsMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Update STKMC
			DoUpdate($STKMCDir);
		}
		elsif ($menuselection eq "2")
		{
			# Update BackupToolDir
			DoUpdate($BackupToolDir);
		}
		elsif ($menuselection eq "3")
		{
			# Update Startup
			DoUpdate($StartupDir);
			if (! -d $BinDir)
			{
				print "Binary dir $BinDir not found, creating...\n";
				system("mkdir -p $BinDir");
			}
			system("cp $StartupDir/supertuxkart $BinDir");
			system("cp $StartupDir/startsupertuxkart $SUPERTUXKARTDIR");
		}
	}
}

sub MainMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$SUPERTUXKARTDIR/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 stk_config.xml',
                                      '7', 'Edit myconfig.xml',
                                      '8', 'Backup STK',
                                      '9', 'View STK Log',
                                      '10', 'Kill STK Process',
                                      '11', 'Edit intro.txt',
                                      '12', 'Update Utils',
                                      'q', 'Quit STKMC' ] );
}

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 STKMC..." );
		exit 0;
	}
	if ($menuselection eq "1")
	{
                if ($d->yesno( text => "Confirm starting the server", text => "Are you sure you want to start the server? You should likely use option #10 instead..." ))
                {
                        system("$StartScript start");
                        sleep(10);
                }
	}
	elsif ($menuselection eq "2")
	{
		if ($d->yesno( text => "Confirm stopping the server", text => "Are you sure you want to shut down the server?" ))
		{
			system("$StartScript stop");
			sleep(5);
		}
	}
	elsif ($menuselection eq "3")
	{
		$d->msgbox( text => "To exit the Super Tux Kart Server console and return to STKMC press CTRL-A CTRL-D" );
		system("screen -r SuperTuxKart");
	}
	elsif ($menuselection eq "4")
	{
		# Turn off respawn
		system("touch $SUPERTUXKARTDIR/nostart");
	}
	elsif ($menuselection eq "5")
	{
		# Turn respawn back on
		if (-f "$SUPERTUXKARTDIR/nostart")
		{
			unlink("$SUPERTUXKARTDIR/nostart");
		}
	}
	elsif ($menuselection eq "6")
	{
		# Edit mudUNIX.sh file
		system("$FileEditor $SUPERTUXKARTDIR/share/supertuxkart/data/stk_config.xml");
	}
	elsif ($menuselection eq "7")
	{
		# Edit myconfig.xml file
		system("$FileEditor $SUPERTUXKARTDIR/share/supertuxkart/data/myconfig.xml");
	}
	elsif ($menuselection eq "8")
	{
                # Run a backup
                system("clear");
                system("$BackupCommand");
                print "Press Enter To Continue";
                my $entered = <STDIN>;
	}
	elsif ($menuselection eq "9")
	{
                # View the log file
                system("$Pager $STKLog");
	}
	elsif ($menuselection eq "10")
	{
		my $running=`ps ax|grep supertuxkart|grep -v grep`;
	        if ($running ne "")
		{
			# Process is running, kill it
			system("killall supertuxkart");
			sleep(5);
		}
	}
	elsif ($menuselection eq "11")
	{
		# Edit intro.txt file
		system("$FileEditor $SUPERTUXKARTDIR/resources/text/intro.txt");
	}
	elsif ($menuselection eq "12")
	{
		# Update Menu
		UpdateTools();
	}
}

exit 0;
