# Description:
# The module provides mechanism of restarting services

########## Confixx(R) 3.0 Professional ############
####### Copyright SWsoft, Inc. 2004-2005 ##########
#### http://www.sw-soft.com - info@sw-soft.com ####


package lib_module_services;

BEGIN {
	use Exporter;
	@ISA = 'Exporter';
	@EXPORT = qw(&reload_daemon &send_sighup);
}

use Proc::ProcessTable;

use lib_module_common;
use lib_module_messaging;

use strict;
no strict 'refs';

# reads variables:
# pm_xxx_reload
# pm_xxx_start
# pm_xxx_user
# pm_xxx_name

# modifies variables:
# none


# reload_daemon(string daemon, string prog, string owner) reload a system daemon
# @return void
# reloads a system daemon given by common name daemon or binary name prog and
# owner.
# Confixx defaults can be overriden via confixx_main.conf pm_$daemon_* ...
sub reload_daemon{
  my ($daemon, $prog, $owner) = @_;
  if($::scriptdebug){
    my $subname = (caller(0))[3];
    print "SUB: $subname ($daemon)\n";
  }
  my ($varname, $return, $initd);
  $return = 0;
  $varname = "main::pm_$daemon\_reload";
	$initd = ${$varname};
  if ( $initd ) {
    $return = system("$initd >/dev/null");
    &soft_error("mlf||scripts_exec_cmd||#1153||$initd") unless $return == 0;

  } else {
    $varname = "main::pm_$daemon\_user";
		$owner = ${$varname};

    $varname = "main::pm_$daemon\_name";
		$prog = ${$varname};

		if ( $prog && $owner ) {
			$return = &send_sighup($prog, $owner);
			&soft_error("mlf||scripts_process_reload||#1154||$prog||$owner") unless $return == 0;
		}
  }

  $varname = "main::pm_$daemon\_start";
	$initd = ${$varname};
  if ( $return  && $initd ) {
    &soft_error("mlf||scripts_exec_cmd||#1155||$initd");
    $return = system( "$initd >/dev/null" );
  }
	return $return;
}

# send_sighup(string prog, string owner) send SIGHUP to process
# @return 0:successful, else:failed
# find a process by given binary name and owner and the send a
# SIGHUP (-1) signal via kill() to that process (reload!)
sub send_sighup{
  my ($prog, $owner) = @_; # e.g. 'httpd', 'root'
  if($::scriptdebug){
    my $subname = (caller(0))[3];
    print "SUB: $subname\n";
  }
  my ($ref, $uid, $return, $rv);
  $rv = 0;
  $uid = (getpwnam($owner))[2];
  if ( $prog && ( $uid =~ /^\d+$/ ) ) {
    $ref = new Proc::ProcessTable;
    $return = 'NOPID';
		my $re = qr/\Q$prog\E\s*(.*)$/;
    foreach my $process ( @{$ref->table} ){
      if ( ( $process->uid == $uid ) && 
					 ( $process->fname =~ /$re/ )
				 ) {
        $return = $process->pid;
        $process->kill(1);
      }
    }

    if ( $return eq 'NOPID' ) {
      &soft_error("mlf||scripts_process_find||#1069||$prog||$owner");
      $rv = 1;
    }

  } else {
    &soft_error("mlf||scripts_process_find||#1070||$prog||$owner");
    $rv = 1;
  }
  return($rv);
}

1;
