# ---- 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");
}

do "core_defines.pl";

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

package main;

sub usage {
	print STDERR "Usage: mwcore <start|stop>\n";
	exit(1);
}
sub err_message{
  my $status=shift;
  my $command=shift;
  print STDERR "Failed to $command Core Services";
  if (defined $error_messages{$status}){
    print STDERR ": $error_messages{$status}";
  }
  print STDERR ".\n";
}
usage() if ($ARGV[0] ne "start" && $ARGV[0] ne "stop");

# the force param comes after the command, check if it's present.
my $force;
my $command=shift @ARGV;
my $user=shift @ARGV;
if( $command eq "stop" && $user eq "-f" ) {
    $force=$user;
    $user=shift @ARGV;
}
my $install_dir = shift @ARGV;
my $data_dir=shift @ARGV;

# Error messages definitions
%error_messages=(1=>"No permissions",
		 2=>"There are still processes connected",
		 4=>"Internal error",
		 5=>"Failed to execute inner watchdog",
		 7=>"Failed to create watchdog termination file",
		 10=>"Failed to launch registry server",
		 11=>"Failed to launch rpcss",
		 12=>"Invalid professional run-time mode group specifier",
		 20=>"No response from inner watchdog");
            

my $stats; #needs to be in scope when it's tested
my $rt_mode = $ENV{MWRT_MODE};
if ($rt_mode eq ""){
	if (open(FILE, "$ENV{MWHOME}/default.mode") == 0) {
		$rt_mode = 'enterprise';
		$ENV{'MWRT_MODE'} = 'enterprise';
	} else {
		$rt_mode = <FILE>;
		chomp($rt_mode);
	}
}
if ($rt_mode eq "classic") {
	print STDERR "*** The 'mwadm' command is irrelevant when running under the 'Classic' run-time mode.\n";
	exit 1;
}
if ( $rt_mode =~ /^professional$/ or $rt_mode =~ /^professional:/) {
	$ENV{MWPROF_STRING} = lc($'); 
	$stats = system("$::fulldir/private_core_services", $command, $force);
} elsif ( $rt_mode =~ /^enterprise$/){
	if (!$user || !$data_dir) {
		print STDERR "Error: $::core_name is not set up correctly on this host.\n";
		exit(1);
	}
	$stats = system("$::fulldir/core_services", $command, $user, 
			$install_dir, $data_dir, $force);
} else {
	print STDERR "Error: Run-time mode is: \'$rt_mode\'; must be "
		. "\'enterprise\' or \'professional\'.\n";
	exit 1;
}

exit(0) if ($stats == 0);
$stats/=256; # system return exit status of Program multiplied by 256
err_message($stats,$command);
exit(1);


