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

use UI::Dialog;
use Term::ReadKey;
use Term::ANSIScreen qw(cls);
use Proc::ProcessTable;
use POSIX qw(strftime);
use Number::Bytes::Human qw(format_bytes parse_bytes);

my $FileEditor = "/bin/nano";
my $InitDName = "/etc/init.d/synchronetbbs";
my $SBBSDIR = "/sbbs";
my $BBS_OWNER = "bbsowner:bbsowner";
my $FILEID = "/root/.fa_settings";
my $BBSIDS = "/root/.ba_settings";
my $BackupCommand = "/root/SyncBackup/syncbackup.pl";
my $PagerCommand = "/usr/bin/less";
my $BACKUP_DIR = "/root/backups";
my $ScreenLog = "/sbbs/SBBSScreen.log";
my $ErrorLog = "/sbbs/data/error.log";
my $GuruLog = "/sbbs/data/guru.log";
my $HackLog = "/sbbs/data/hack.log";
my $SbbsechoLog = "/sbbs/data/sbbsecho.log";
my $SpamLog = "/sbbs/data/spam.log";
my $TelnetCmd = "/usr/bin/telnet";
my $DoorLog = "/opt/doorparty-connector/nohup.out";
my $UpdateCommand = "/usr/bin/git pull";
my $SMCDir = "/root/SynchronetManagementConsole";
my $BackupToolDir = "/root/SyncBackup";
my $StartupDir = "/root/SynchronetStartup";
my $BinDir = "/root/bin";
my $BBSUtils = "/root/bbs_utils";
my $DATADIR = "$SBBSDIR/data";
my $WCCmd = "/usr/bin/wc";
my $MCCmd = "/usr/bin/mc";

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

my $MySettings = "$ENV{'HOME'}/.smcrc";
my $User = $ENV{'USER'};
my $SMC_ver = "1.24.1";
my $Record = "false";	# Are results saved?
my $TempDir = "/tmp";
my $RobotName = "";
my $BotVersion = "";
my $UserName = "";
my $ServerStatus = "foo";
my $WatchdogStatus = "foo";
my $SCFG = "$SBBSDIR/exec/scfg";
my $DEBUG_MODE = "off";

my $CONF_FROM = "";
my $CONF_SUBJECT = "";
my $CONF_GROUPS = "";
my $CONF_FILE = "";

my $RESTORE_COMMAND = "tar xvzf";

my $AnyBad = 0;
my $PidFile = "/sbbs/ctrl/sbbs.pid";

if ($User ne "root")
{
	print "Synchronet BBS Management Console v$SMC_ver\n";
	print "==============================================\n";
	print "Not running as root.\nSMC has to be run as root for some functions to work properly.\n";
	print "Do you want to run it anyway? (Y/n): ";
	my $entered = <STDIN>;
	chop($entered);
	if (($entered eq "n") || ($entered eq "N") || ($entered eq "no") || ($entered eq "NO"))
	{
		exit(0);
	}
}

sub IsRunning
{
        if (! -f $PidFile)
        {
                print "PID file not found\n";
                return("nope");
        }
        # PID file found, checking for process
        open(my $fh, '<:encoding(UTF-8)', $PidFile);
        if ($fh eq "")
        {
                print "Could not open file '$PidFile' for reading $!";
                return("nope");
        }
        my $CurLine = 0;
        while (my $row = <$fh>)
        {
                chomp $row;
                print "Read pid file '$row'\n";
                $CurLine = $row;
        }
        close($fh);
        if (kill(0, $CurLine) != 1)
        {
                return "nope";
        }
        return "sbbs";
}

my $running=IsRunning();

if ($ENV{'EDITOR'})
{
        $FileEditor = $ENV{'EDITOR'};
}

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

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

sub ReadConfigFile
{
	# 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 "sbbsdir")
			{
				$SBBSDIR = $Setting;
			}
			if ($Command eq "backupcommand")
			{
				$BackupCommand = $Setting;
			}
			if ($Command eq "pagercommand")
			{
				$PagerCommand = $Setting;
			}
			if ($Command eq "bbsowner")
			{
				$BBS_OWNER = $Setting;
			}
			if ($Command eq "fileid")
			{
				$FILEID = $Setting;
			}
			if ($Command eq "bbsids")
			{
				$BBSIDS = $Setting;
			}
			if ($Command eq "debugmode")
			{
				$DEBUG_MODE = $Setting;
			}
			if ($Command eq "backupdir")
			{
				$BACKUP_DIR = $Setting;
			}
			if ($Command eq "screenlog")
			{
				$ScreenLog = $Setting;
			}
			if ($Command eq "errorlog")
			{
				$ErrorLog = $Setting;
			}
			if ($Command eq "gurulog")
			{
				$GuruLog = $Setting;
			}
			if ($Command eq "hacklog")
			{
				$HackLog = $Setting;
			}
			if ($Command eq "sbbsecholog")
			{
				$SbbsechoLog = $Setting;
			}
			if ($Command eq "spamlog")
			{
				$SpamLog = $Setting;
			}
			if ($Command eq "telnetcmd")
			{
				$TelnetCmd = $Setting;
			}
			if ($Command eq "updatecommand")
			{
				$UpdateCommand = $Setting;
			}
		}
		close($FH);
	}
	else
	{
		# Store defaults
		open (my $FH, ">", $MySettings) or die "Could not create default file '$MySettings' $!";
		print $FH "sbbsdir=$SBBSDIR\n";
		print $FH "fileeditor=$FileEditor\n";
		print $FH "backupcommand=$BackupCommand\n";
		print $FH "pagercommand=$PagerCommand\n";
		print $FH "bbsowner=$BBS_OWNER\n";
		print $FH "fileid=$FILEID\n";
		print $FH "bbsid=$BBSIDS\n";
		print $FH "backupdir=$BACKUP_DIR\n";
		print $FH "debugmode=$DEBUG_MODE\n";
		print $FH "screenlog=$ScreenLog\n";
		print $FH "errorlog=$ErrorLog\n";
		print $FH "gurulog=$GuruLog\n";
		print $FH "hacklog=$HackLog\n";
		print $FH "sbbsecholog=$SbbsechoLog\n";
		print $FH "spamlog=$SpamLog\n";
		print $FH "telnetcmd=$TelnetCmd\n";
		print $FH "doorlog=$DoorLog\n";
		print $FH "updatecommand=$UpdateCommand\n";
		close($FH);
	}
}

my $menuselection = "";

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

sub CheckWatchdogStatus
{
	my $wdrunning=`ps ax|grep startsynchronetbbs|grep -v grep`;
	chop($wdrunning);
	$wdrunning = substr($running, -18);
	if ($wdrunning ne "startsynchronetbbs")
	{
		$WatchdogStatus = "Stopped";
	}
	else
	{
		$WatchdogStatus = "Running";
	}
}

sub CheckServerStatus
{
	$running=IsRunning();
	if ($running ne "sbbs")
	{
		$ServerStatus = "Stopped";
	}
	else
	{
		$ServerStatus = "Running";
	}
}

sub ReadConfig
{
	my $Keyword;
	my $Keyvalue;

	$CONF_FROM = "";
	$CONF_SUBJECT = "";
	$CONF_GROUPS = "";

	open(my $fh, '<', $CONF_FILE) or die "Could not open file '$CONF_FILE' $!";
	while (my $row = <$fh>)
	{
		chomp $row;
		($Keyword, $Keyvalue) = split(':', $row);
		if (substr($row, 0, 5) eq "from")
		{
			$CONF_FROM = substr($row, 5);
		}
		elsif (substr($row, 0, 8)  eq "subject")
		{
			$CONF_SUBJECT = substr($row, 8);
		}
		elsif (substr($row, 0, 7) eq "groups")
		{
			$CONF_GROUPS = $Keyvalue;
		}
	}
	close($fh);
	if ($CONF_FROM eq "")
	{
		die ("FROM not set in config file");
	}
	if ($CONF_SUBJECT eq "")
	{
		die ("SUBJECT not set in config file");
	}
	if ($CONF_GROUPS eq "")
	{
		die ("GROUPS not set in config file");
	}
}

sub KillBBS
{
	PrintDebugCommand("killall sbbs");
	system("killall sbbs");
}

sub ForceKillBBS
{
	PrintDebugCommand("killall -s9 sbbs");
	system("killall -s9 sbbs");
}

sub MainMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$SBBSDIR/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 Off Respawn',
                                      '5', 'Turn On Respawn',
                                      '6', 'Edit sbbs.ini',
                                      '7', 'Run scfg',
                                      '8', 'Backup / Restore',
                                      '9', 'Set File Owners',
                                      '10', 'Call Outs Menu',
                                      '11', 'Edit Settings',
                                      '12', 'Reset BBS Proc.',
                                      '13', 'Posting Tools',
                                      '14', 'Log Files',
                                      '15', 'Telnet to BBS',
                                      '16', 'Update Tools',
                                      '17', 'View Bad Packets',
                                      '18', 'Edit Text Files',
                                      '19', 'Fun Tools',
                                      'q', 'Quit SMC' ] );
}

sub ProcesKillMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$SBBSDIR/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)
	{
		ProcesKillMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Reset the server process
			print "Killing sbbs process, please wait...";
			KillBBS();
			sleep(10);
		}
		elsif ($menuselection eq "2")
		{
			# Force-kill server process
			if ($d->yesno( text => "Confirm force-killing BBS process", text => "Are you *SURE* you want to force kill the BBS process?\nYou should first try the \#1 option and see if that works" ))
			{
				print "Force-killing sbbs process, please wait for 10 seconds...";
				ForceKillBBS();
				sleep(10);
			}
		}
	}
}
sub PostingToolsMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$SBBSDIR/nostart")
	{
		$WantRespawn="OFF";
	}

	$menuselection = $d->menu( title => "Posting Tools Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Edit Announce.txt',
                                      '2', 'Edit FilePost.txt',
                                      '3', 'Edit FilePostBottom.txt',
                                      '4', 'Run BBS Announce',
                                      '5', 'Run FileAnnounce',
                                      '6', 'Edit BBS IDs',
                                      '7', 'Edit File IDs',
                                      'q', 'Main Menu' ] );
}

sub PostingTools
{
	while (-1)
	{
		PostingToolsMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Edit Announce.txt file
			PrintDebugCommand("$FileEditor $SBBSDIR/exec/Announce.txt");
			system("$FileEditor $SBBSDIR/exec/Announce.txt");
		}
		elsif ($menuselection eq "2")
		{
			# Edit FilePost.txt file
			PrintDebugCommand("$FileEditor $SBBSDIR/exec/FilePost.txt");
			system("$FileEditor $SBBSDIR/exec/FilePost.txt");
		}
		elsif ($menuselection eq "3")
		{
			# Edit FilePostBottom.txt file
			PrintDebugCommand("$FileEditor $SBBSDIR/exec/FilePostBottom.txt");
			system("$FileEditor $SBBSDIR/exec/FilePostBottom.txt");
		}
		elsif ($menuselection eq "4")
		{
			# Read in config
			$CONF_FILE = $BBSIDS;
			ReadConfig();
	
			# Run BBS Announce
			PrintDebugCommand("/root/bbs_utils/bbs_announce.pl --bbsowner='$CONF_FROM' --bbssubj='$CONF_SUBJECT' --groups='$CONF_GROUPS'");
			system("/root/bbs_utils/bbs_announce.pl --bbsowner='$CONF_FROM' --bbssubj='$CONF_SUBJECT' --groups='$CONF_GROUPS'");
		}
		elsif ($menuselection eq "5")
		{
			# Read in config
			$CONF_FILE = $FILEID;
			ReadConfig();

			# Run File Announce
			PrintDebugCommand("/root/bbs_utils/file_announce.pl --bbsowner='$CONF_FROM' --bbssubj='$CONF_SUBJECT' --group='$CONF_GROUPS'");
			system("/root/bbs_utils/file_announce.pl --bbsowner='$CONF_FROM' --bbssubj='$CONF_SUBJECT' --group='$CONF_GROUPS'");
		}
		elsif ($menuselection eq "6")
		{
			# Edit BBSIDS.txt file
			if (! -f $BBSIDS)
			{
				PrintDebugCommand("cp /root/SynchronetManagementConsole/BBS_ANN_DEF.txt $BBSIDS");
				system("cp /root/SynchronetManagementConsole/BBS_ANN_DEF.txt $BBSIDS");
			}
			PrintDebugCommand("$FileEditor $BBSIDS");
			system("$FileEditor $BBSIDS");
		}
		elsif ($menuselection eq "7")
		{
			# Edit FILEID.txt file
			if (! -f $FILEID)
			{
				PrintDebugCommand("cp /root/SynchronetManagementConsole/FILE_ANN_DEF.txt $FILEID");
				system("cp /root/SynchronetManagementConsole/FILE_ANN_DEF.txt $FILEID");
			}
			PrintDebugCommand("$FileEditor $FILEID");
			system("$FileEditor $FILEID");
		}
	}
}

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

	$menuselection = $d->menu( title => "Log File Viewer Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Screen Log File',
                                      '2', 'Error Log File',
                                      '3', 'Guru Log File',
                                      '4', 'Hack Log File',
                                      '5', 'Sbbsecho Log File',
                                      '6', 'Spam Log File',
                                      '7', 'Clear Screen',
                                      '8', 'Clear Error',
                                      '9', 'Clear Guru',
                                      '10', 'Clear Hack',
                                      '11', 'Clear SBBS Echo',
                                      '12', 'Clear Spam',
                                      '13', 'DoorParty Log',
                                      '14', 'Clear All Logs',
                                      'q', 'Main Menu' ] );
}

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

	$menuselection = $d->menu( title => "Backup Tools Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Run Backup',
                                      '2', 'Restore Backup',
                                      'q', 'Main Menu' ] );
}

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

	$menuselection = $d->menu( title => "Fun Tools Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Who is Online',
                                      '2', 'Last Logins',
                                      '3', 'Disk Free',
                                      '4', 'Current Proc',
                                      'q', 'Main Menu' ] );
}

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

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 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 SMC
			DoUpdate($SMCDir);
		}
		elsif ($menuselection eq "2")
		{
			# Update BackupToolDir
			DoUpdate($BackupToolDir);
		}
		elsif ($menuselection eq "3")
		{
			# Update Startup
			DoUpdate($StartupDir);
		}
		elsif ($menuselection eq "4")
		{
			# Update bbs_utils
			DoUpdate($BBSUtils);
		}
	}
}

sub BadPacketsMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$SBBSDIR/nostart")
	{
		$WantRespawn="OFF";
	}
	$menuselection = $d->menu( title => "Bad Packets Management Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'List Bad Packets',
                                      '2', 'Remove All Bad',
                                      '3', 'Browse Files',
                                      'q', 'Main Menu' ] );
}

sub GetNumBadPackets
{
	#$AnyBad = system("ls $DATADIR|grep bad\$ \|wc");
	$AnyBad = `ls $DATADIR|grep bad\$ \|$WCCmd `;
}

sub EditTextFilesMenu
{
	my $WantRespawn="ON";
	CheckServerStatus();
	if (-f "$SBBSDIR/nostart")
	{
		$WantRespawn="OFF";
	}
	$menuselection = $d->menu( title => "Edit Text Files Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Edit ip.can',
                                      '2', 'Edit email.can',
                                      '3', 'Edit host.can',
                                      '4', 'Edit name.can',
                                      '5', 'Edit password.can',
                                      '6', 'Edit phone.can',
                                      '7', 'Edit subject.can',
                                      '8', 'Edit zipmsg.txt',
                                      '9', 'Edit ircmotd.txt',
                                      '10', 'Edit answer.msg',
                                      '11', 'Edit badpassword.msg',
                                      '12', 'Edit bullseye.asc',
                                      '13', 'Edit feedback.msg',
                                      '14', 'Edit newuser.msg',
                                      '15', 'Edit system.msg',
                                      '16', 'Edit welcome.msg',
                                      '17', 'Edit banner1.msg',
                                      '18', 'Edit banner2.msg',
                                      '19', 'Edit banner3.msg',
                                      '20', 'Edit alias.cfg',
                                      'q', 'Main Menu' ] );
}

sub EditTextFiles
{
	while (-1)
	{
		EditTextFilesMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		if ($menuselection eq "1")
		{
			# Edit ip.can
			system ("$FileEditor /sbbs/text/ip.can");
		}
		elsif ($menuselection eq "2")
		{
			# Edit email.can
			system ("$FileEditor /sbbs/text/email.can");
		}
		elsif ($menuselection eq "3")
		{
			# Edit host.can
			system ("$FileEditor /sbbs/text/host.can");
		}
		elsif ($menuselection eq "4")
		{
			# Edit name.can
			system ("$FileEditor /sbbs/text/name.can");
		}
		elsif ($menuselection eq "5")
		{
			# Edit password.can
			system ("$FileEditor /sbbs/text/password.can");
		}
		elsif ($menuselection eq "6")
		{
			# Edit phone.can
			system ("$FileEditor /sbbs/text/phone.can");
		}
		elsif ($menuselection eq "7")
		{
			# Edit subject.can
			system ("$FileEditor /sbbs/text/subject.can");
		}
		elsif ($menuselection eq "8")
		{
			# Edit zipmsg.txt
			system ("$FileEditor /sbbs/text/zipmsg.txt");
		}
		elsif ($menuselection eq "9")
		{
			# Edit ircmotd.txt
			system ("$FileEditor /sbbs/text/ircmotd.txt");
		}
		elsif ($menuselection eq "10")
		{
			# Edit answer.msg
			system ("$FileEditor /sbbs/text/answer.msg");
		}
		elsif ($menuselection eq "11")
		{
			# Edit badpassword.msg
			system ("$FileEditor /sbbs/text/badpassword.msg");
		}
		elsif ($menuselection eq "12")
		{
			# Edit bullseye.asc
			system ("$FileEditor /sbbs/text/bullseye.asc");
		}
		elsif ($menuselection eq "13")
		{
			# Edit feedback.msg
			system ("$FileEditor /sbbs/text/feedback.msg");
		}
		elsif ($menuselection eq "14")
		{
			# Edit newuser.msg
			system ("$FileEditor /sbbs/text/newuser.msg");
		}
		elsif ($menuselection eq "15")
		{
			# Edit system.msg
			system ("$FileEditor /sbbs/text/system.msg");
		}
		elsif ($menuselection eq "16")
		{
			# Edit welcome.msg
			system ("$FileEditor /sbbs/text/welcome.msg");
		}
		elsif ($menuselection eq "17")
		{
			# Edit banner1.msg
			system ("$FileEditor /sbbs/text/banner1.msg");
		}
		elsif ($menuselection eq "18")
		{
			# Edit banner2.msg
			system ("$FileEditor /sbbs/text/banner2.msg");
		}
		elsif ($menuselection eq "19")
		{
			# Edit banner3.msg
			system ("$FileEditor /sbbs/text/banner3.msg");
		}
		elsif ($menuselection eq "20")
		{
			# Edit alias.cfg
			system ("$FileEditor /sbbs/ctrl/alias.cfg");
		}
	}
}

sub ManageBadPackets
{
	while (-1)
	{
		BadPacketsMenu();
		GetNumBadPackets();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		if ($menuselection eq "3")
		{
			# Delete the bad packets
			system("$MCCmd -u /sbbs/data /tmp");
			next;
		}
		if ($AnyBad == 0)
		{
			system("clear");
			print "No bad packets found\n";
			print "--- Press Enter To Continue ---";
			my $entered = <STDIN>;
		}
		elsif ($menuselection eq "1")
		{
			# List bad packets
			system("clear");
			system ("ls -l $DATADIR/*.bad");
			print "--- Press Enter To Continue ---";
			my $entered = <STDIN>;
		}
		elsif ($menuselection eq "2")
		{
			# Delete the bad packets
			system("clear");
			system ("rm $DATADIR/*.bad");
			print "All bad packet files removed\n";
			print "--- Press Enter To Continue ---";
			my $entered = <STDIN>;
		}
	}
}

sub GetWhichBackup
{
	my $UsedFile = 0;
	opendir(DIR, $BACKUP_DIR) or die $!;
	my @file_list;
	while ( my $file = readdir(DIR))
	{
		# We only want files
		next unless (-f "$BACKUP_DIR/$file");

		# Use a regular expression to find files ending in .tgz
		next unless ($file =~ m/\.tgz$/);
		push @file_list, "$BACKUP_DIR/$file";
	}
	closedir(DIR);

	#print scalar @file_list;
	system("clear");
	print "Backup\tBackup Date\t\tSize\n";
	for my $file (sort
		{
			my @a_stat = stat($a);
			my @b_stat = stat($b);
			$b_stat[8] <=> $a_stat[8];
		} @file_list ) {
			$UsedFile++;
			my @stat = stat ("$file");
			my $size = format_bytes($stat[7], bs => 1000);
			print "$UsedFile\t" . strftime("%m/%d/%Y %H:%M:%S", localtime($stat[8])) . "\t$size ($file)\n";
		};

	#Ask user which one
	while(-1)
	{
		print "Restore which backup? (1-5): ";
		my $Chosen = <STDIN>;
		chop ($Chosen);
		if ((lc($Chosen) eq "q") || (lc($Chosen) eq "quit") || ($Chosen eq ""))
		{
			return "";
		}
		my $IntChosen = int($Chosen);
		if (($IntChosen >= 1) && ($IntChosen <= 5))
		{
			return $Chosen;
		}
	}
}

sub DoRestore
{
	my $WhichBackup = "";

	# Get which backup they want
	$WhichBackup = GetWhichBackup();
	if ($WhichBackup eq "")
	{
		print "No backup selected\n";
		return;
	}
	print "Using backup $WhichBackup...\n";

	# Turn off respawn
	PrintDebugCommand("touch $SBBSDIR/nostart");
	system("touch $SBBSDIR/nostart");
	# Kill the server process
	print "Killing SBBS process, please wait...";
	KillBBS();
	sleep(10);
	# Create new folder
	print "Creating new folder, please wait...";
	PrintDebugCommand("mkdir $SBBSDIR-new");
	system("mkdir $SBBSDIR-new");
	PrintDebugCommand("touch $SBBSDIR-new/nostart");
	system("touch $SBBSDIR-new/nostart");
	# Swap folders
	print "Swapping folders, please wait...";
	PrintDebugCommand("mv $SBBSDIR $SBBSDIR-keep");
	system("mv $SBBSDIR $SBBSDIR-keep");
	PrintDebugCommand("mv $SBBSDIR-new $SBBSDIR");
	system("mv $SBBSDIR-new $SBBSDIR");
	PrintDebugCommand("rm -r $SBBSDIR-keep");
	system("rm -r $SBBSDIR-keep");

	# Do the restore
	chdir ("/");
	PrintDebugCommand("$RESTORE_COMMAND $BACKUP_DIR/syncbackup-$WhichBackup.tgz");
	system("$RESTORE_COMMAND $BACKUP_DIR/syncbackup-$WhichBackup.tgz");
	# Change owners
	PrintDebugCommand("chown -R $BBS_OWNER /sbbs");
	system("chown -R $BBS_OWNER /sbbs");
	unlink("$SBBSDIR/nostart");
}

sub LogFiles
{
	while (-1)
	{
		LogFilesMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Screen log file
			PrintDebugCommand("Displaying Screen log file");
			system("$PagerCommand $ScreenLog");
		}
		elsif ($menuselection eq "2")
		{
			# Error Log File
			PrintDebugCommand("Displaying Error log file");
			system("$PagerCommand $ErrorLog");
		}
		elsif ($menuselection eq "3")
		{
			# Guru Log File
			PrintDebugCommand("Displaying Guru log file");
			system("$PagerCommand $GuruLog");
		}
		elsif ($menuselection eq "4")
		{
			# Hack Log File
			PrintDebugCommand("Displaying Hack log file");
			system("$PagerCommand $HackLog");
		}
		elsif ($menuselection eq "5")
		{
			# Sbbsecho Log File
			PrintDebugCommand("Displaying Sbbsecho log file");
			system("$PagerCommand $SbbsechoLog");
		}
		elsif ($menuselection eq "6")
		{
			# Spam Log File
			PrintDebugCommand("Displaying Spam log file");
			system("$PagerCommand $SpamLog");
		}
		elsif ($menuselection eq "7")
		{
			# Screen log file
			if (-f $ScreenLog)
			{
				PrintDebugCommand("Deleting Screen log file");
				unlink($ScreenLog);
			}
		}
		elsif ($menuselection eq "8")
		{
			# Error log file
			if (-f $ErrorLog)
			{
				PrintDebugCommand("Deleting Error log file");
				unlink($ErrorLog);
			}
		}
		elsif ($menuselection eq "9")
		{
			# Guru log file
			if (-f $GuruLog)
			{
				PrintDebugCommand("Deleting Guru log file");
				unlink($GuruLog);
			}
		}
		elsif ($menuselection eq "10")
		{
			# Hack log file
			if (-f $HackLog)
			{
				PrintDebugCommand("Deleting Hack log file");
				unlink($HackLog);
			}
		}
		elsif ($menuselection eq "11")
		{
			# Sbbsecho log file
			if (-f $SbbsechoLog)
			{
				PrintDebugCommand("Deleting Sbbsecho log file");
				unlink($SbbsechoLog);
			}
		}
		elsif ($menuselection eq "12")
		{
			# Spam log file
			if (-f $SpamLog)
			{
				PrintDebugCommand("Deleting Spam log file");
				unlink($SpamLog);
			}
		}
		elsif ($menuselection eq "13")
		{
			# Door Party Log File
			PrintDebugCommand("Displaying Door Party log file");
			system("$PagerCommand $DoorLog");
		}
		elsif ($menuselection eq "14")
		{
			# Clear all logs
			if (-f $SpamLog)
			{
				PrintDebugCommand("Deleting Spam log file");
				unlink($SpamLog);
			}
			if (-f $SbbsechoLog)
			{
				PrintDebugCommand("Deleting SBBS Echo log file");
				unlink($SbbsechoLog);
			}
			if (-f $HackLog)
			{
				PrintDebugCommand("Deleting Hack log file");
				unlink($HackLog);
			}
			if (-f $GuruLog)
			{
				PrintDebugCommand("Deleting Guru log file");
				unlink($GuruLog);
			}
			if (-f $ErrorLog)
			{
				PrintDebugCommand("Deleting Error log file");
				unlink($ErrorLog);
			}
			if (-f $ScreenLog)
			{
				PrintDebugCommand("Deleting Screen log file");
				unlink($ScreenLog);
			}
		}
	}
}

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

	$menuselection = $d->menu( title => "Call-Outs Menu", text => "Server is $ServerStatus and respawn is $WantRespawn - Select one:",
                            list => [ '1', 'Call DOVENet',
                                      '2', 'Call UseNet',
                                      '3', 'Call GameNet',
                                      '4', 'Call SFNet',
                                      '5', 'Call WeedNet',
                                      '6', 'Call RetroNet',
                                      '7', 'Call RetroNeo',
                                      'q', 'Main Menu' ] );
}

sub CallOuts
{
	while (-1)
	{
		CallOutsMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Force a call-out to Dovenet
			PrintDebugCommand("touch $SBBSDIR/data/qnet/vert.now");
			system("touch $SBBSDIR/data/qnet/vert.now");
		}
		elsif ($menuselection eq "2")
		{
			# Force a call-out to Usenet/Newslink
			PrintDebugCommand("touch $SBBSDIR/data/newslink.now");
			system("touch $SBBSDIR/data/newslink.now");
		}
		elsif ($menuselection eq "3")
		{
			# Force a call-out to GameNet
			PrintDebugCommand("touch $SBBSDIR/data/qnet/gamenet.now");
			system("touch $SBBSDIR/data/qnet/gamenet.now");
		}
		elsif ($menuselection eq "4")
		{
			# Force a call-out to SFNet
			PrintDebugCommand("touch $SBBSDIR/data/qnet/sfnet.now");
			system("touch $SBBSDIR/data/qnet/sfnet.now");
		}
		elsif ($menuselection eq "5")
		{
			# Force a call-out to Weednet
			PrintDebugCommand("touch $SBBSDIR/data/qnet/weednet.now");
			system("touch $SBBSDIR/data/qnet/weednet.now");
		}
		elsif ($menuselection eq "6")
		{
			# Force a call-out to Retronet
			PrintDebugCommand("touch $SBBSDIR/data/qnet/freeway.now");
			system("touch $SBBSDIR/data/qnet/freeway.now");
		}
		elsif ($menuselection eq "7")
		{
			# Force a call-out to Retronet Neo
			PrintDebugCommand("touch $SBBSDIR/data/qnet/retrone.now");
			system("touch $SBBSDIR/data/qnet/retrone.now");
		}
	}
}

sub BackupTools
{
	while (-1)
	{
		BackupToolsMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Run a backup
			PrintDebugCommand("$BackupCommand");
			system("$BackupCommand");
			print "Press Enter To Continue";
			my $entered = <STDIN>;
		}
		elsif ($menuselection eq "2")
		{
			# Do a restore
			DoRestore();
			print "Press Enter To Continue";
			my $entered = <STDIN>;
		}
	}
}

sub FunTools
{
	while (-1)
	{
		FunToolsMenu();
		if (($menuselection eq "CANCEL") || ($menuselection eq "ESC") || ($menuselection eq "") || ($menuselection eq "q") || ($menuselection eq "Q"))
		{
			return;
		}
		elsif ($menuselection eq "1")
		{
			# Who is online
			system("clear");
			system("w");
			print "Press Enter To Continue:";
			my $entered = <STDIN>;
		}
		elsif ($menuselection eq "2")
		{
			# Last logins
			system("clear");
			system("last | $PagerCommand");
		}
		elsif ($menuselection eq "3")
		{
			# Disk free space
			system("clear");
			system("df -h");
			print "Press Enter To Continue:";
			my $entered = <STDIN>;
		}
		elsif ($menuselection eq "4")
		{
			# Running processes
			system("clear");
			print "Press \"q\" To Exit. Press Enter To Continue:";
			my $entered = <STDIN>;
			system("top");
		}
	}
}

ReadConfigFile();

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 SMC..." );
		exit 0;
	} 
	if ($menuselection eq "1")
	{
		# Check if wtachdog is running
		CheckWatchdogStatus();
		if ($WatchdogStatus eq "Running")
		{
			system("clear");
			print "Watchdog is already running\n";
			sleep(3);
		}
		elsif ($d->yesno( text => "Confirm starting the server watchdog", text => "Are you *SURE* you want to start the server watchdog?" ))
		{
			PrintDebugCommand("$InitDName start");
			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? You should likely use option #12 instead..." ))
		{
			PrintDebugCommand("$InitDName stop");
			system("$InitDName stop");
			sleep(10);
		}
	}
	elsif ($menuselection eq "3")
	{
		$d->msgbox( text => "To exit the SBBS console and return to SMC press CTRL-A CTRL-D" );
		PrintDebugCommand("screen -r SBBS");
		system("screen -r SBBS");
	}
	elsif ($menuselection eq "4")
	{
		# Turn off respawn
		PrintDebugCommand("touch $SBBSDIR/nostart");
		system("touch $SBBSDIR/nostart");
	}
	elsif ($menuselection eq "5")
	{
		# Turn respawn back on
		if (-f "$SBBSDIR/nostart")
		{
			unlink("$SBBSDIR/nostart");
		}
	}
	elsif ($menuselection eq "6")
	{
		# Edit sbbs.ini file
		PrintDebugCommand("$FileEditor $SBBSDIR/ctrl/sbbs.ini");
		system("$FileEditor $SBBSDIR/ctrl/sbbs.ini");
	}
	elsif ($menuselection eq "7")
	{
		# Run scfg
		PrintDebugCommand("$SCFG");
		system("$SCFG");
		# Set owner of /sbbs
		PrintDebugCommand("chown -R $BBS_OWNER /sbbs");
		system("chown -R $BBS_OWNER /sbbs");
	}
	elsif ($menuselection eq "8")
	{
		# Go to backup menu
		BackupTools();
	}
	elsif ($menuselection eq "9")
	{
		# Set owner of /sbbs
		PrintDebugCommand("chown -R $BBS_OWNER /sbbs");
		system("chown -R $BBS_OWNER /sbbs");
	}
	elsif ($menuselection eq "10")
	{
		# Call-out menu
		CallOuts();
	}
	elsif ($menuselection eq "11")
	{
		# Edit Settings
		PrintDebugCommand("$FileEditor $MySettings");
		system("$FileEditor $MySettings");
		ReadConfigFile();
	}
	elsif ($menuselection eq "12")
	{
		# Reset the server process menu
		ProcessKill();
	}
	elsif ($menuselection eq "13")
	{
		# Posting tools
		PostingTools();
	}
	elsif ($menuselection eq "14")
	{
		# Log files
		LogFiles();
	}
	elsif ($menuselection eq "15")
	{
		# Connect via telnet
		system("clear");
		system("$TelnetCmd localhost");
	}
	elsif ($menuselection eq "16")
	{
		# Update tools
		UpdateTools();
	}
	elsif ($menuselection eq "17")
	{
		# Manage any bad packets
		ManageBadPackets();
	}
	elsif ($menuselection eq "18")
	{
		# Edit various text files
		EditTextFiles();
	}
	elsif ($menuselection eq "19")
	{
		# Go to fun menu
		FunTools();
	}
}

exit 0;
