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

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

my $FileEditor = "/bin/nano";
my $InitDName = "/home/wowowner/bin/azerothcore";
my $AZCDIR = "/home/wowowner/azerothcore";
my $BackupCommand = "/home/wowowner/Azerothcore-Backup/azerothbackup -snapshot";
my $GameLog = "/home/wowowner/OpenRCT2/OpenRCT2Screen.log";
my $Pager = "/usr/bin/less";
my $AZMCDir = "/home/wowowner/Azerothcore-Manager";
my $BackupToolDir = "/home/wowowner/Azerothcore-Backup";
my $StartupToolDir = "/home/wowowner/Azerothcore-Startup";
my $CONFIG_DIR = "/home/wowowner/azerothcore/env/dist/etc";
my $UpdateCommand = "/usr/bin/git pull";
my $DEBUG_MODE = "off";
my $AUTH_SERVICE = "/home/wowowner/azerothcore/startazerothauth";
my $WORLD_SERVICE = "/home/wowowner/azerothcore/startazerothworld";

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

my $AZMC_ver = "1.0.0";
my $Record = "false";	# Are results saved?
my $TempDir = "/tmp";
my $RobotName = "";
my $BotVersion = "";
my $UserName = "";
my $ServerStatus = "foo";
my $AuthStatus = "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 => "AzerothCore Management Console v$AZMC_ver", height => 20, width => 65, listheight => 5,
	order => [ 'ascii', 'cdialog', 'xdialog' ]);

my $windowtitle = "Welcome to the AzerothCore Management Console!";
my $enjoyedtitle = "We hope you enjoyed AZMC!";
my $introtext =
"This is the AzerothCore Management Console, a utility for AzerothCore operators to manage their servers from a text UI 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 worldserver|grep -v grep`;
	if ($running ne "")
	{
		$ServerStatus = "Running";
	}
	else
	{
		$ServerStatus = "Stopped";
	}
	$running=`ps ax|grep authserver|grep -v grep`;
	if ($running ne "")
	{
		$AuthStatus = "Running";
	}
	else
	{
		$AuthStatus = "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 "$AZCDIR/nostart")
	{
		$WantRespawn="OFF";
	}
	$menuselection = $d->menu( title => "Update Utilities Menu", text => "Server $ServerStatus, Auth Server $AuthStatus - Select one:",
                            list => [ '1', 'Update AZMC',
                                      '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 AZMC
			DoUpdate($AZMCDir);
		}
		elsif ($menuselection eq "2")
		{
			# Update BackupToolDir
			DoUpdate($BackupToolDir);
		}
		elsif ($menuselection eq "3")
		{
			# Update StartupToolDir
			DoUpdate($StartupToolDir);
		}
	}
}

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

        $menuselection = $d->menu( title => "Process Kill Menu", text => "World Server $ServerStatus, Auth Server $AuthStatus - Select one:",
                            list => [ '1', 'Kill Auth Server',
                                      '2', 'Kill World Server',
                                      'q', 'Main Menu' ] );
}

sub ProcessKill
{
        while (-1)
        {
		CheckServerStatus();
                ProcesKillMenu();
                if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
                {
                        return;
                }
                elsif ($menuselection eq "1")
                {
			if ($AuthStatus eq "Running")
			{
				# Reset the auth server process
				print "Restarting Auth Server, please wait...";
				system("service ac-authserver restart");
				sleep(1);
			}
			else
			{
				print "Auth server not running...";
				sleep(3);
			}
                }
                elsif ($menuselection eq "2")
                {
			if ($ServerStatus eq "Running")
                        {
                                # Reset the world server process
                                print "Restarting World Server, please wait...";
                                system("service ac-worldserver restart");
                                sleep(1);
                        }
                        else
                        {
                                print "World server not running...";
                                sleep(3)
                        }
                }
        }
}

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

	$menuselection = $d->menu( title => "Main Menu", text => "World Server $ServerStatus, Auth Server $AuthStatus - Select one:",
                            list => [ '1', 'Start All Servers',
                                      '2', 'World Console',
                                      '3', 'Auth Console',
                                      '4', 'Edit Authservice',
                                      '5', 'Edit Worldservice',
                                      '6', 'Snapshot Backup',
                                      '7', 'Kill Game Process',
                                      '8', 'Update Utils',
                                      'q', 'Quit AZMC' ] );
}

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 AZMC..." );
		exit 0;
	}
	if ($menuselection eq "1")
	{
		system("$InitDName authserver start");
		system("$InitDName worldserver start");
		sleep(3);
	}
	elsif ($menuselection eq "2")
	{
		$d->msgbox( text => "To exit the AzerothCore World console and return to AZMC press CTRL-A CTRL-D" );
		system("screen -r WorldServer");
	}
	elsif ($menuselection eq "3")
	{
		$d->msgbox( text => "To exit the AzerothCore Auth console and return to AZMC press CTRL-A CTRL-D" );
		system("screen -r AuthServer");
	}
	elsif ($menuselection eq "4")
	{
		# Edit Authserver conf
		system("$FileEditor $CONFIG_DIR/authserver.conf");
	}
	elsif ($menuselection eq "5")
	{
		# Edit Authserver conf
		system("$FileEditor $CONFIG_DIR/worldserver.conf");
	}
	elsif ($menuselection eq "6")
	{
                # Run a backup
                system("clear");
                system("$BackupCommand");
                print "Press Enter To Continue";
                my $entered = <STDIN>;
	}
	elsif ($menuselection eq "7")
	{
		ProcessKill();
	}
	elsif ($menuselection eq "8")
	{
		# Update Menu
		UpdateTools();
	}
}

exit 0;
