#!/usr/bin/perl
#
# $Id: peg.pl,v 1.16 2009/01/21 21:21:15 anderson Exp $
# 
# Daemonize the xapply so that it can manage all of the peg persistent samplers;

use strict;
use lib  '/usr/local/lib/sac/perl'.join('.', unpack('c*', $^V)),
	'/usr/local/lib/sac';

use POSIX;
use Pod::Usage;
use Getopt::Long;
Getopt::Long::Configure('posix_default');
Getopt::Long::Configure('bundling_override');
Getopt::Long::Configure('no_ignore_case_always');

# RH7.3's perl is 5.6.1. Makes me sad :(
if ($] > 5.008) {
	Getopt::Long::Configure('no_auto_help');
	Getopt::Long::Configure('no_auto_version');
} else {
	Getopt::Long::Configure('no_ignorecase');
} 

$main::VERSION = '$Id: peg.pl,v 1.16 2009/01/21 21:21:15 anderson Exp $';

$0 =~ m!.*/(.+)!;
my $progname = $1;
my $pidfile = undef;

GetOptions(
	'version|V'	=> sub { print "$main::VERSION\r\n"; exit 0 },
	'help|h|?'	=> sub { pod2usage(-exitval => 0, 1) },
	'pidfile|P:s'	=> \$pidfile
) or pod2usage("Invalid option");

my $pid = undef;

# Become a proper daemon
chdir '/';
POSIX::setsid();
if ($pid = fork) {
	if (defined $pidfile) { 
		open PIDFILE, ">$pidfile" or 
		die "Unable to open pidfile: $pidfile";
		print PIDFILE "$pid";
		close PIDFILE;
	}
	exit 0;
} 
if (!defined $pid) {
	die "There is no fork, only spoon!\n";
}

# Close input/output
open STDOUT, ">/dev/null";
open STDERR, ">/dev/null";
open STDIN, "</dev/null";
# We are now a proper daemon

# * exec causes problems for redhat's daemon functions
# * leave as system
system '/usr/local/bin/xapply -i/dev/null -f -P100 \'sleep $(($RANDOM%%5)); exec %[1]\' /usr/local/etc/peg.conf';

__END__

=head1 NAME

peg - run configured PEG samplers from one program

=head1 SYNOPSIS
 

 peg
 peg -h
 peg -V

=head1 OPTIONS

=item B<-h>, B<--help>

display help message

=item B<-V>, B<--version>

display version information

=head1 DESCRIPTION

peg is a program that runs all of the configured samplers in a persistent 
process instead of using cron to launch the samplers at specified intervals.

This process should run as a non-privileged user, and should be started by 
init.

Alternately, peg samplers may be started by the non-privileged user using
cron to start the samplers at the appropriate interval ( don't use the -p
option for cron based starting ).

=head1 RELATED FILES

peg.conf
