#!/usr/bin/perl
#
# $Id: daemonize.pl,v 1.4 2010/06/10 19:57:53 tswan Exp $
# 
# Simple background/daemon launcher

use POSIX;
use Getopt::Long;
use Pod::Usage;
use strict;

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

Getopt::Long::Configure('posix_default');
#RH7.3's perl has issues with no_auto_help and no_auto_version !-(
#Getopt::Long::Configure('no_auto_help');
#Getopt::Long::Configure('no_auto_version');
Getopt::Long::Configure('bundling_override');
Getopt::Long::Configure('no_ignore_case_always');

$main::VERSION = '$Id: daemonize.pl,v 1.4 2010/06/10 19:57:53 tswan Exp $';

$0 =~ m!.*/(.+)!;
my $progname = $1;
# We might want these later, so here they are
my ($exec,$system) = (undef,undef);

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

my $pid = undef;

# Become a proper daemon: cd /, and close all input/output channels
chdir '/';
POSIX::setsid();
open STDOUT, ">/dev/null";
open STDERR, ">/dev/null";
open STDIN, "</dev/null";

if ($pid = fork) {
	exit 0;
} 
if (!defined $pid) {
	die "There is no fork, only spoon!\n";
}

if ($system) {
	system "@ARGV";
	
}
exec "@ARGV";

__END__

=head1 NAME

daemonize - run a command completely detached

=head1 SYNOPSIS
 

 daemonize
 daemonize -x C<command> C<args>
 daemonize -s C<command> C<args>
 daemonize -h
 daemonize -V

=head1 OPTIONS

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

display help message

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

display version information

=item B<-x>, B<--exec>

exec C<command> replacing the current process

Note: this can cause problems for init scripts

=item B<-s>, B<--system>

run C<command> as a normal subproces

=head1 DESCRIPTION

daemonize runs a command completely detached from the controlling terminal.


