# ---- This is a perl file ----

BEGIN {
  $curdir=`dirname "$0"`;
  chomp($curdir);
  $pwd="`pwd`";
  chomp($pwd);
  if($curdir eq "."){ $fulldir="$pwd";}
  elsif ($curdir =~ /^\//) {$fulldir=$curdir;}
  else {$fulldir="$pwd/$curdir";}
  push(@INC,"$fulldir","$fulldir/tools");
}

# set autoflush for STDOUT
select(STDOUT);
$|=1;

# enumeration log names
$eNoSuchLog = 0;
$eRegistryLog = 1;
$eRpcssLog = 2;

# names of log files
$sReg = "regss";
$sRpc = "rpcss";
$rpcss_logname = "mwrpcss_event";

# main 
if( ($#ARGV == 1) || ($#ARGV < 2) ) {
	run_mwlog();
}

if ("-view" eq $ARGV[1]) {
	view($ARGV[2]);
	exit(0);
}

# not view need at least three parameters
if ( 	( $#ARGV < 3) || 
	( "-level" eq $ARGV[1] ) ||
	( "-maxsize" eq $ARGV[1] ) ||
	( "-basesize" eq $ARGV[1] ) ) {
	run_mwlog();
}

sub run_mwlog() {
	system ("@ARGV");
	exit $status;
}

sub getEnum {
	my ($name) = @_;
	return $eRegistryLog if ($name eq $sReg);   
	return $eRpcssLog if ($name eq $sRpc);

	print STDERR "Invalid log name $name.\n";
	return $eNoSuchLog;
}

sub view {
	my ($name) = @_;
	my $eLog = getEnum($name);
	return 1 if ($eLog eq $eNoSuchLog);

	if ($eLog eq $eRpcssLog) {
		$name = $rpcss_logname;
	}
	my $mwrt_mode = $ENV{MWRT_MODE};
	unless($mwrt_mode) {
	    if (open(MWDEF, "$fulldir/../mwset_rtmode|") ) {
		my $output = <MWDEF>;
		$output =~ /\'(\w+)\'/;
		$mwrt_mode = $1;
		close(MWDEF);
	    }
            # safe side
	    $mwrt_mode = "enterprise" unless $mwrt_mode;
	}

	my $logs = "";

	if ($mwrt_mode eq "enterprise" ) {
		my $conf_file = "/etc/mainwin.conf";
		open (FILE, "<$conf_file");

		# search for env 'CORE_DATA' in /etc/mainwin.conf
		while ($line = <FILE>) {
			if ($line =~ /CORE_DATA=(.*)/){
				$logs = "$1/logs/$name.log";
				break;
			}
		}
		if ($line = "") {
			print STDERR "Unable to find the variable CORE_DATA in file $conf_file.\n";
			print $line;
			exit (1);
		}
		close(FILE);
	}
	else {
		# proffesional mode , check if it's "professional:<group_name>"

		my $group = "";
		if ($mwrt_mode =~ /professional:(.*)/) {
			$group = "$1/";
		}
		
		my $mwuser_dir = "$ENV{MWUSER_DIRECTORY}";
		my $hostname   =`uname -n`;chomp($hostname);
		my $thedir = $ENV{MWCORE_PRIVATE_DATA} || "$mwuser_dir/core_data";
		$logs = "$thedir/$group$hostname/logs/$name.log";
	
	}

	# print log file
	if (!open (FILE, "<$logs")) {
		print "Unable to open file $logs.\n";
	}
	else {
		while ($line = <FILE>) {
			print $line;
		}
		close (FILE);
	}
	
}
