#!/usr/bin/perl


my $input = "0";
my $logDir = `cat ./halfStats.cfg | grep -v '#' | grep 'logDir'`;
($tag, $path) = split("=", $logDir);
chomp($path);

my $count = 0;

do 
{
    system("clear");
    print "\n\nNOTE: It is best to shut the server down before\n";
    print "      using this program.\n\n";
    print "Select an option from the menu:\n";
    print "\t(P) = re(P)lace a name in the logs\n";
    print "\t(M) = re(M)ove a name from the logs\n";
    print "\t(F) = (F)ix blank names in the logs\n";
    print "\t(Q) = Quit\n\n";
    print "Your choice: ";

    $input = lc($input = <STDIN>);
    chomp($input);
    if($input eq "q"){die "\n** Exitting..\n\n";}
    elsif($input eq "p"){&replace($path);}
    elsif($input eq "m"){&remove($path);}
    elsif($input eq "f"){&fix($path);}

} while ($input ne "q");

sub replace
{
    my $path = $_[0];
    my $check = &catLogs($path);
    if($check ne "0")
    {
	print "\nEnter the name you wish to replace: ";
	my $badName = <STDIN>;
	chomp($badName);
    
	print "Enter the name to replace $badName with: ";
	my $goodName = <STDIN>;
	chomp($goodName);

	open(FILE, "<$check") || die "$! [$check]\n";
	my @array = <FILE>;
	close(FILE);

	open(FILE, ">$check") || die "$! [$check]\n";
	foreach $line (@array)
	{
	    $line =~ s/$badName/$goodName/g;
	    print FILE "$line";
	}
	close(FILE);
	print "* Done..\n";
    }
    else
    {
	print "** Log merging error prevents name replacement\n";
    }
}

sub remove
{
    my $path = $_[0];

    my $check = &catLogs($path);
    if($check ne "0")
    {
	print "\nEnter the name you wish to remove: ";
	my $name = <STDIN>;
	chomp($name);
	system("cat $check | grep -v '$name' > /tmp/remove.$$");
	system("mv -f /tmp/remove.$$ $check");
	print "Done..\n";
    }
    else
    {
	print "** Log merging error prevents name removal\n";
    }

}

sub fix
{
    my $path = $_[0];
    my $check = &catLogs($path);
    if($check ne "0")
    {
	system("cat $check | grep -v '<-1>' > /tmp/fix.$$");
	system("mv -f /tmp/fix.$$ $check");
	print "* Done..\n";
    }
    else
    {
        print "** Log merging error prevents fixes\n";
    }
}

sub catLogs
{
    my $path = $_[0];
    my $check = "";

    print "\n* Merging logs into a master log file..\n";
    system("cat $path/*.log > $path/logs.txt");
    $check = `ls -1 $path | grep 'logs.txt'`;
    chomp($check);
    
    if($check ne "")
    {
	print "* Successful log merge..\n";
	print "* Removing old files..\n";
	system("rm -f $path/*.log");
	print "* Renaming temporary file..\n";
	system("mv $path/logs.txt $path/logfile.log");
	$returnVal = "$path/logfile.log";
    }
    else
    {
	print "** Error merging logs..\n";
	print "** Cleaning up..\n";
	system("rm -f $path/logs.txt");
	print "Done..\n";
	$returnVal = 0;
    }
    return($returnVal);
}



