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

do "core_install.pl";

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

package main;
# prints usage of this script
sub usage {
  if ($mode eq "install" || $mode eq "setup") {
    print STDERR "Usage: ${mode}.mwcore [-instdir <installation dir>] [-datadir <data dir>] [-adm <mainwin administrator>][-dcom_passwd <dcom password>]\n";
  }
  else {
    print STDERR "Usage: ${mode}.mwcore\n";
  }
  exit (1);
} 

#######################################################################
# handle arguments
#######################################################################

$special_user = undef;
$mode = undef;
$install_dir = undef;
$data_dir = undef;
$dcom_passwd=undef;
$do_start=1;
$repair = 0;
$interactive = 1;
$status;
$automatic=0;
$trace=0;
$status=0; # exit status
# read command line
$mode=shift @ARGV;
$mode =~ s/^\-//; # remove '-' from the mode
$type=shift @ARGV;

for ($i=0; $i<@ARGV; $i++) {
  if ($ARGV[$i] eq "-repair") {$repair = 1; next;}
  if ($ARGV[$i] eq "-install") {$mode = "install"; next;}
  if ($ARGV[$i] eq "-uninstall") {$mode = "uninstall"; next;}
  if ($ARGV[$i] eq "-setup") {$mode = "setup"; next;}
  if ($ARGV[$i] eq "-unset") {$mode = "unset"; next;}
  if ($ARGV[$i] eq "-batch") {$interactive = 0; next;}
  if ($ARGV[$i] eq "-instdir" && $ARGV[$i+1])
    {$install_dir = $ARGV[$i+1]; $i++; next;} 
  if ($ARGV[$i] eq "-datadir" && $ARGV[$i+1])
    {$data_dir = $ARGV[$i+1]; $i++; next;} 
  if ($ARGV[$i] eq "-adm" && $ARGV[$i+1])
    {$special_user = $ARGV[$i+1]; $i++; next;}
  if ($ARGV[$i] eq "-dcom_passwd" && $ARGV[$i+1])
    {$dcom_passwd = $ARGV[$i+1]; $i++; next;}
  if ($ARGV[$i] eq "-not_start")
    {$do_start=0;next;}
  if ($ARGV[$i] eq "-help")
    {usage();}
  usage();
}

usage() if (! defined($mode));
if ( defined($special_user) && defined($install_dir) && defined($data_dir)){
  $automatic=1;
}
#######################################################################
# set globals
#######################################################################
$mwos=`uname`;chomp($mwos);
$MWOS=`$::fulldir/../getplatinfo os`;chomp($MWOS);
$MWARCH=`$::fulldir/../getplatinfo arch`;chomp($MWOS);
$MWCONFIG_NAME=`$::fulldir/../getplatinfo config`;chomp($MWCONFIG_NAME);

$DLL_SUFFIX=$ENV{DLL_SUFFIX};

$date=`date '+%m%d%Y'`;chomp($date);
$hostname=`uname -n`;chomp($hostname);
if (defined $ENV{'MWDEBUG'}){
  $trace = $ENV{'MWDEBUG'};
}
$headline='='x (70)."\n";
my $config = new config($config_file);
my $core = new core($config_file, $config);
my $orig_dir;
# Set User Name and Check if the user is root
# Core installation will run only from super user (root)
$id=`id`;
@all_id=split(/\(/,$id);
($username,@trush)=split(/\)/,$all_id[1]);
if ($username ne "root"){ 
  $type = $mode;
  $type .= "ed" if ($mode eq "install" || $mode eq "uninstall");
  $type = "set up" if ($mode eq "setup");

  #print STDERR "$::core_name requires root privileges to be $type.\nPlease run the script as the superuser.\n";
  print STDERR "This setup script may only be run by root. Please log in as root and run the script again. Aborting...\n";
  exit 1;
}

#######################################################################
# start working
#######################################################################

$logfile=undef;
$core->create_log($mode);
::trace(1,"logfile is $logfile\n");
chdir("/var/tmp"); # if something crashes, we don't want a core file
# to be created on disk

if ($mode eq "install") {
  $status=install();
}
elsif ($mode eq "uninstall") {
  $status=uninstall();
}
elsif ($mode eq "setup") {
  $status=setup();
}
elsif ($mode eq "unset") {
  $status=unsetup();
}

exit($status);

#######################################################################
### get_log_count ###
#######################################################################
sub get_log_count{
  my $logdir = shift;
  my $count_type = shift;
  my $count;
  if (! -d $logdir){
    system("/bin/mkdir -p $logdir 2> /dev/null;chmod a+wrx $logdir;echo 1 > $logdir/.count_$count_type;chmod a+w $logdir/.count_$count_type");
    $count=1;
  }
  elsif (! -f "$logdir/.count_$count_type"){
    system(" echo 1 > $logdir/.count_$count_type;chmod a+rw $logdir/.count_$count_type");
    $count=1;
  }
  else{
      $count=`cat $logdir/.count_$count_type`;chomp($count);
      $count++;
      system("rm -f $logdir/.count_$count_type 2>/dev/null;echo $count > $logdir/.count_$count_type;chmod a+rw $logdir/.count_$count_type");
  }
  return $count;
}

#######################################################################
### installation ###
#######################################################################
sub install {
  my $new_version = $core->get_core_version("$::fulldir/$::version_file");
  my $upgrade = 0;
  my $install_status = undef;

  # check if core services are already installed
  if (($install_status = $core->is_core_installed())>0) {
      print "*** The MSC is already installed and set up on this host. Aborting...\n";
    # Check if upgrade is needed
      ::my_exit();
      
  }

  # check data that user provided, and ask him for data he didn't
  # provide (install dir, data dir, system admin)
  
  $install_dir = $core->get_dir("installation", 1, $::default_inst_dir, $install_dir); #1=root access needed
  
  $data_dir = $install_dir."/mwcoredata";
  $data_dir .= "/$hostname";
  $special_user = $core->get_special_user($special_user);
  
 
  my $status = $core->install($install_dir, $data_dir, $special_user, $upgrade);
  if ($status == 0) {
    ::printlog("\nInstallation completed successfully.\n\n");
    print STDERR "\nInstallation completed successfully.\n\n";
  }
  elsif ($status == 1) {
    ::printlog("\nInstallation failed.\n\n");
    print STDERR "\nInstallation failed.\n\n";
  }
  else {
    ::printlog("\nInstallation completed with errors.\n\n");
    print STDERR "\nInstallation completed with errors.\n\n";
  }
  $count=get_log_count("$data_dir/logs","install");
  $final_log="$data_dir/logs/mwcore_install.log.$count";
  system("mv $::logfile  $final_log");
  print STDERR "\nA transcript of this installation was saved in $final_log\n\n";
  return $status;
}

#######################################################################
### uninstallation ###
#######################################################################
sub uninstall {
  $special_user = $config->get_sys_admin();
  $data_dir = $config->get_path_to_data();
  $install_dir = $config->get_path_to_core();
  
  if (!$special_user){$special_user="root";} # by default user is root 
  if (!$install_dir){
    my @dirs=split(/\//,$::fulldir); # fulldir is <install_dir>/utils/tools
    do {
      $dir=pop (@dirs);
    }
    while ($dir ne "bin");
    $install_dir=join("/",@dirs);
  }
  if (!$data_dir) {
    ::printlog("Error: Either $::core_name is not installed, or the installation is corrupt.\nAre you sure $::core_name is installed on this host? [y/n]: ");
    print STDERR "Error: Either $::core_name is not installed, or the installation is corrupt.\nAre you sure $::core_name is installed on this host? [y/n]: ";
    exit(1) if (!::user_agrees());

    $core->complete_config_info(\$install_dir, \$data_dir, \$special_user);
  }
  
  # ask user if he wants to unsintall core services
  if (! $core->is_uninstall_accepted()) {
    
    ::my_exit();
  }
  my $status = $core->uninstall($install_dir, $data_dir, $special_user);
  if ($status == 0) {
    ::printlog("\nUninstall completed successfully.\n\n");
    print STDERR "\nUninstall completed successfully.\n\n";
  }
  elsif ($status == 1) {
    ::printlog("\nUninstallation failed.\n\n");
    print STDERR "\nUninstallation failed.\n\n";
  }
  else {
    ::printlog("\nUninstallation completed with warnings.\n\n");
    print STDERR "\nUninstallation completed with warnings.\n\n";
  }
  
  print STDERR "\nA transcript of this uninstallation was saved in $::logfile\n\n";
  return $status;
}

#######################################################################
### setup ###
#######################################################################
sub setup {
  # check if core services are already installed
  if ($core->is_core_installed()>0) {
    ::printlog("$::core_name is already set up on this host.\n");
    print STDERR "$::core_name is already set up on this host.\n";
    exit(0);
  }

  if (! $install_dir) {
    $install_dir = $core->get_dir_from_user("installation", $::default_inst_dir);
  }
  if (! -d $install_dir ||
      ::is_dir_empty($install_dir)) {
    ::printlog("Error: '$install_dir' does not appear to be a valid $::core_name installation directory.\n");
    print STDERR "Error: '$install_dir' does not appear to be a valid $::core_name installation directory.\n";
    ::my_exit();
  }
  $data_dir = $core->get_dir("data", 0, $::default_data_dir, $data_dir);
  $data_dir .= "/$hostname";

  $special_user = $core->get_special_user($special_user);

  my $status = $core->setup($install_dir, $data_dir, $special_user, $do_start);
  if ($status == 0) {
    ::printlog("\nSetup completed successfully.\n\n");
    print STDERR "\nSetup completed successfully.\n\n";
  }
  elsif ($status == 1) {
    ::printlog("\nSetup failed.\n\n");
    print STDERR "\nSetup failed.\n\n";
  }
  else {
    ::printlog("\nSetup completed with errors.\n\n");
    print STDERR "\nSetup completed with errors.\n\n";
  }
  $count=get_log_count("$data_dir/logs","setup");
  $final_log="$data_dir/logs/mwcore_setup.log.$count";
  system("mv $::logfile  $final_log");
  print STDERR "\nA transcript of this setup was saved in $final_log\n\n";
  return $status;
}

#######################################################################
### unsetup ###
#######################################################################
sub unsetup {
  $special_user = $config->get_sys_admin();
  $data_dir = $config->get_path_to_data();
  $install_dir = $config->get_path_to_core();
  
  if (!$special_user){$special_user="root";} # by default user is root 
  if (!$install_dir){
    my @dirs=split(/\//,$::fulldir); # fulldir is <install_dir>/utils/tools
    do {
      $dir=pop (@dirs);
    }
    while ($dir ne "bin");
    $install_dir=join("/",@dirs);
  }
  if (!$data_dir) {
    ::printlog("Error: Either $::core_name is not set up on this host, or the setup information is corrupt.\nAre you sure $::core_name is set up on this host? [y/n]: ");
    print STDERR "Error: Either $::core_name is not set up on this host, or the setup information is corrupt.\nAre you sure $::core_name is set up on this host? [y/n]: ";
    exit(1) if (!::user_agrees());

    $core->complete_config_info(\$install_dir, \$data_dir, \$special_user);
  }
 
  if (!$automatic){ 
    # ask user if he wants to unsintall core services
    if (! $core->is_unsetup_accepted()) {
     ::my_exit();
    }   
  } 
  my $status = $core->unsetup($special_user, $install_dir, $data_dir);
  if ($status == 0) {
    ::printlog("\nUnset completed successfully.\n\n");
    print STDERR "\nUnset completed successfully.\n\n";
  }
  elsif ($status == 1) {
    ::printlog("\nUnset failed.\n\n");
    print STDERR "\nUnset failed.\n\n";
  }
  else {
    ::printlog("\nUnset completed with warnings.\n\n");
    print STDERR "\nUnset completed with warnings.\n\n";
  } 
  $count=get_log_count("$data_dir/logs","unsetup");
  $final_log="$data_dir/logs/mwcore_unsetup.log.$count";
  system("mv $::logfile  $final_log");
  print STDERR "\nA transcript of this unsetup was saved in $final_log\n\n";
  return $status;
}

