# -*-perl-*-

# $id$

# $Log: Init.plm,v $
# Revision 1.3  2015/05/04 20:30:22  timc
# updates for systemd on rhel7
#
# Revision 1.2  2003/12/15 16:28:35  thomas
# check-in for 0.1.1
#
# Revision 1.1.1.1  2003/12/02 14:47:35  thomas
# Initial version before export to 0.1.1
#

package What::Trigger::Init;

use strict;
use Data::Dumper;

use base qw(What::Trigger);


sub Init {
  my $trigger = shift;
  my $node = shift;  # The config object
  my $section = shift;
  my $what = shift;
  my $params = shift;

  my ($init, $is_systemd, $rc_dir, $newinit, @cmd);
  my $failed = 0;

  $init = $params->{init};
  if (!defined ($init)) {
    $what->err ("What::Trigger::Init needs the name of an init.\n");
    $failed++;
  }
  if (!exists $params->{functions}) {
    $what->err ("What::Trigger::Init needs a list of functions to exectute.\n");
    $failed++;
  }
  if ($failed) {
    $what->err ("Params follows:\n" . Dumper ($params) . "\n");
    return 0;
  }

  defined ($rc_dir = $section->getattrs ($section, attr => 'rc_dir', ))
    or return 0;

  #if systemd_dest is defined this host uses systemd so set is_systemd 
  #and why doesn't defined work here?  I don't know.  Perl sucks.
  $is_systemd = $section->getattrs ($section, attr => 'systemd_dest');
	if ($is_systemd) {
		$is_systemd = 1;
	} else {
		$is_systemd = 0;
	}

  # Maybe do a name substitution on the init name
  $newinit = $section->getattrs (
				 $section,
				 path => '/Triggers/vars/rc_name_map',
				 attr => $init,
				);
  defined ($newinit) and $init = $newinit;

  foreach (split (/,/, $params->{functions})) {
	s/\s*$//;
	s/^\s*//;

  	if ($is_systemd) {
		@cmd = ("systemctl $_ $init");
  	} else {
      		@cmd = ("$rc_dir/$init", $_);
  	} #else

	$what->debug (1, "%s\n", join (' ', @cmd));
	system (@cmd);
  } #foreach
  return 1;
}

###############################################################################

=head1 NAME

What::Triggers::Init -- Run one or more function on a system rc file.

=head1 PARAMS

The params structure for this trigger must be supplied with the following:

=over 4

B<init> -- contains the base name of the rc file to be run

B<functions> -- contains a comma-separated list of the functions to be
run on the rc file.

=back

This module uses the global standard variable B</rc_dir> as the
location of the init script directory.

=head1 EXAMPLES

This module has the ability to remap rc file names, so that generic rc
names can be included in the configuration, and resolved to actual rc
files when the trigger is run.  The following pair would use a virtual
rc file B<INETD> which would map to different inits on different
systems:

<node path="/Inetd" >
  <trigger path="/Init" init="INETD" functions="stop,start" />
</node>

Then, on system a:

<node path="/Triggers/vars/rc_name_map" INETD="inetd" />

While on system b:

<node path="/Triggers/vars/rc_name_map" INETD="xinetd" />

=cut

###############################################################################

1;
