#!/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/openmpowner/bin/openmp";
my $OPENMPDIR = "/home/openmpowner/Open.mp";
my $BackupCommand = "/home/openmpowner/OpenmpBackup/openmpbackup.pl snapshot";
my $OMPLog = "/home/openmpowner/Open.mp/log.txt";
my $OMCDir = "/home/openmpowner/OpenmpManagementConsole";
my $BackupToolDir = "/home/openmpowner/OpenmpBackup";
my $StartupDir = "/home/openmpowner/OpenmpStartup";
my $UpdateCommand = "/usr/bin/git pull";
my $BinDir = "/home/openmpowner/bin";
my $DEBUG_MODE = "off";
my $PagerCommand = "/usr/bin/less";
my $DiskFreeCmd = "/usr/bin/df -h";
my $MailQueueCmd = "/usr/bin/mailq";
my $ShellCommand = "/usr/bin/bash";

my $OMC_Config = "$ENV{HOME}/.openmprc";

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

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

my $defaultconfig = <<"END_TEMPLATE";
# What editor to use
$FileEditor
# What is the startup script path
$InitDName
# Where is the Open.mp install directory
$OPENMPDIR
# What is the backup command
$BackupCommand
# WHere is the log file
$OMPLog
# Where is the OMC directory
$OMCDir
# Where is the OMC Backup dir
$BackupToolDir
# Where is the OMC Startup script folder
$StartupDir
# What is the command to get updates
$UpdateCommand
# Where does this user store their local tools
$BinDir
# Is debug mode on?
$DEBUG_MODE
# What should we user for paging output
$PagerCommand
# How do we get free space?
$DiskFreeCmd
# How do we get the mail queue?
$MailQueueCmd
# How do we spawn a shell?
$ShellCommand
END_TEMPLATE

if (! -f $OMC_Config)
{
	print "Settings file $OMC_Config not found, creating it...\n";
	open(FILEOUT, '>', $OMC_Config) or die $!;
        print FILEOUT "$defaultconfig";
	close(FILEOUT);
	system("$FileEditor $OMC_Config");
	print "Preferences created, please rerun the script\n";
	exit 0;
}

my $num_args = $#ARGV + 1;
if ($num_args != 0)
{
	if ($ARGV[0] eq "prefs")
        {
                system("$FileEditor $OMC_Config");
                exit 0;
        }
}

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>;
}

open(FILEIN, '<', $OMC_Config) or die $!;
my $LastLine = 0;
while(<FILEIN>)
{
	# print $_;
	if ((substr($_, 0, 1) eq "#") || ($_ eq ""))
	{
		# skip over comments and blank lines
		next;
	}
	chop();
	if ($LastLine == 0)
	{
		$FileEditor = $_;
		$LastLine++;
		PrintDebugCommand("saw file editor '$FileEditor'\n");
	}
	elsif ($LastLine == 1)
	{
		$InitDName = $_;
		$LastLine++;
		PrintDebugCommand("saw initdname '$InitDName'\n");
	}
	elsif ($LastLine == 2)
	{
		$OPENMPDIR = $_;
		$LastLine++;
		PrintDebugCommand("saw openmpdir '$OPENMPDIR'\n");
	}
	elsif ($LastLine == 3)
	{
		$BackupCommand = $_;
		$LastLine++;
		PrintDebugCommand("saw backup command '$BackupCommand'\n");
	}
	elsif ($LastLine == 4)
	{
		$OMPLog = $_;
		$LastLine++;
		PrintDebugCommand("saw omp log '$OMPLog'\n");
	}
	elsif ($LastLine == 5)
	{
		$OMCDir = $_;
		$LastLine++;
		PrintDebugCommand("saw omc dir '$OMCDir'\n");
	}
	elsif ($LastLine == 6)
	{
		$BackupToolDir = $_;
		$LastLine++;
		PrintDebugCommand("saw backup tool dir '$BackupToolDir'\n");
	}
	elsif ($LastLine == 7)
	{
		$StartupDir = $_;
		$LastLine++;
		PrintDebugCommand("saw startup dir '$StartupDir'\n");
	}
	elsif ($LastLine == 8)
	{
		$UpdateCommand = $_;
		$LastLine++;
		PrintDebugCommand("saw update command '$UpdateCommand'\n");
	}
	elsif ($LastLine == 9)
	{
		$BinDir = $_;
		$LastLine++;
		PrintDebugCommand("saw bindir '$BinDir'\n");
	}
	elsif ($LastLine == 10)
	{
		$DEBUG_MODE = $_;
		$LastLine++;
		PrintDebugCommand("saw debug mode '$DEBUG_MODE'\n");
	}
	elsif ($LastLine == 11)
	{
		$PagerCommand = $_;
		$LastLine++;
		PrintDebugCommand("saw pager command '$PagerCommand'\n");
	}
	elsif ($LastLine == 12)
	{
		$DiskFreeCmd = $_;
		$LastLine++;
		PrintDebugCommand("saw disk free command '$DiskFreeCmd'\n");
	}
	elsif ($LastLine == 13)
	{
		$MailQueueCmd = $_;
		$LastLine++;
		PrintDebugCommand("saw dmail quere command '$MailQueueCmd'\n");
	}
	elsif ($LastLine == 14)
	{
		$ShellCommand = $_;
		$LastLine++;
		PrintDebugCommand("saw shell command '$ShellCommand'\n");
	}
}
close(FILEIN);

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

my $windowtitle = "Welcome to the Open.mp Management Console!";
my $enjoyedtitle = "We hope you enjoyed OMC!";
my $introtext =
"This is the Open.mp Management Console, a utility for Open.mp 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 omp-server|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 SystemUtilMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$OPENMPDIR/nostart")
	{
		$WantRespawn="OFF";
	}
	$menuselection = $d->menu( title => "System Utilities Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Linux Users',
                                      '2', 'Active Processes',
                                      '3', 'Login History',
                                      '4', 'Disk Free',
                                      '5', 'Mail Queue',
                                      'q', 'Main Menu' ] );
}

sub SystemUtilities
{
	while (-1)
	{
		SystemUtilMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Who's logged in and system load
			system("clear");
                        system("w");
                        print "Press Enter To Continue:";
                        my $entered = <STDIN>;
		}
		elsif ($menuselection eq "2")
		{
			# Display active processes
			system("clear");
                        print "Press \"q\" To Exit. Press Enter To Continue:";
                        my $entered = <STDIN>;
                        system("top");
		}
		elsif ($menuselection eq "3")
		{
			# Linux Login History
			system("clear");
                        system("last | $PagerCommand");
		}
		elsif ($menuselection eq "4")
		{
			# Disk Space
			system("clear");
	                system("$DiskFreeCmd");
                        print "Press Enter To Continue:";
                        my $entered = <STDIN>;
		}
		elsif ($menuselection eq "5")
		{
			# Disk Space
			system("clear");
	                system("$MailQueueCmd");
                        print "Press Enter To Continue:";
                        my $entered = <STDIN>;
		}
	}
}

sub UpdateToolsMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$OPENMPDIR/nostart")
	{
		$WantRespawn="OFF";
	}
	$menuselection = $d->menu( title => "Update Utilities Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Update OMC',
                                      '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 OMC
			DoUpdate($OMCDir);
		}
		elsif ($menuselection eq "2")
		{
			# Update BackupToolDir
			DoUpdate($BackupToolDir);
		}
		elsif ($menuselection eq "3")
		{
			# Update Startup
			DoUpdate($StartupDir);
		}
	}
}

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

        $menuselection = $d->menu( title => "Process Kill Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Request Clean',
                                      '2', 'Force Kill',
                                      '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 ($ServerStatus eq "Running")
			{
				# Reset the server process
				print "Killing mud process, please wait...";
				system("killall omp-server");
				sleep(10);
			}
			else
			{
				print "Process not running...";
				sleep(3)
			}

                }
                elsif ($menuselection eq "2")
                {
                        # Force-kill server process
                        if ($d->yesno( text => "Confirm force-killing Open.mp process", text => "Are you *SURE* you want to force kill the Open.mp process?\nYou should first try the \#1 option and see if that works" ))
                        {
				if ($ServerStatus eq "Running")
				{
					print "Force-killing mud process, please wait for 5 seconds...";
					system("killall -s9 omp-server");
					sleep(5);
				}
				else
				{
					print "Process not running...";
					sleep(3)
				}
                        }
                }
        }
}

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

	$menuselection = $d->menu( title => "Main Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Start Watchdog',
                                      '2', 'Stop Watchdog',
                                      '3', 'Server Console',
                                      '4', 'Turn Respawn Off',
                                      '5', 'Turn Respawn On',
                                      '6', 'Edit config.json',
                                      '7', 'Edit bans.json',
                                      '8', 'Backup Open.mp',
                                      '9', 'View Open.mp Log',
                                      '10', 'Kill Open.mp Process',
                                      '11', 'Update Utils',
                                      '12', 'Ubuntu Version',
                                      '13', 'Utilities',
                                      '14', 'Spawn Shell',
                                      'q', 'Quit OMC' ] );
}

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 OMC..." );
		exit 0;
	}
	if ($menuselection eq "1")
	{
                if ($d->yesno( text => "Confirm starting the server watchdog", text => "Are you sure you want to start the server watchdog? You should likely use option #10 instead..." ))
                {
                        system("$InitDName start");
                        sleep(10);
                }
	}
	elsif ($menuselection eq "2")
	{
		if ($d->yesno( text => "Confirm stopping the server watchdog", text => "Are you sure you want to shut down the server watchdog?" ))
		{
			system("$InitDName stop");
			sleep(5);
		}
	}
	elsif ($menuselection eq "3")
	{
		$d->msgbox( text => "To exit the Open.mp console and return to OMC press CTRL-A CTRL-D" );
		system("screen -r Openmp");
	}
	elsif ($menuselection eq "4")
	{
		# Turn off respawn
		system("touch $OPENMPDIR/nostart");
	}
	elsif ($menuselection eq "5")
	{
		# Turn respawn back on
		if (-f "$OPENMPDIR/nostart")
		{
			unlink("$OPENMPDIR/nostart");
		}
	}
	elsif ($menuselection eq "6")
	{
		# Edit config.json file
		system("$FileEditor $OPENMPDIR/config.json");
	}
	elsif ($menuselection eq "7")
	{
		# Edit bans.json file
		system("$FileEditor $OPENMPDIR/bans.json");
	}
	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("$PagerCommand $OMPLog");
	}
	elsif ($menuselection eq "10")
	{
		ProcessKill();
	}
	elsif ($menuselection eq "11")
	{
		# Update Menu
		UpdateTools();
	}
	elsif ($menuselection eq "12")
	{
		# Display Ubuntu version
                system("clear");
		system("$OMCDir/ubuntuversion");
		print "Press Enter To Continue: ";
		my $entered = <STDIN>;
	}
	elsif ($menuselection eq "13")
	{
		# Run utilities
		SystemUtilities();
	}
	elsif ($menuselection eq "14")
	{
		# Run bash shell
		system("clear");
		print "About to spawn a shell. Enter \"exit\" to exit and return to OMC\n";
		print "Press Enter To Continue:";
		my $entered = <STDIN>;
		system("clear");
		chdir("$ENV{HOME}");
		system("$ShellCommand");
	}
}

exit 0;
