#! perl -w
##
## Name: 
##
## cfx5detach
##
## Purpose: 
##
## Launch a detached sub-process. 
## 
## Synopsis:
##
#S cfx5detach [-help] [-verbose] [-wait] <command>
##
## []  denotes an optional argument. 
## |   separates mutually exclusive arguments. 
## ... following an argument indicates that it may be repeated.
## <>  denotes that substitution of a suitable value is required. All other
##     arguments are keywords, some of which may have a short form.
##
## Arguments:
##
## -help
## -h
##     Print this message.
##
## -verbose
## -v
##     Specifying this option may result additional output being sent to 
##     the standard output file (normally the screen).
##
## -wait
##     Wait for command to finish before exiting.
##
## <command>
##     Command to be detached.
##

# get the standard CFX-5 library directory
BEGIN {
  if ($0 =~ m!^([a-z]:)?[\\/]!i) {
    # it's an absolute path, use it as-is
    (my $nd=$0) =~ s!(perllib[\\/])?[^\\/]*$!!i;
    unshift @INC, "$nd/perllib";
  } else {
    # wrap this in an eval, and if it fails, pray ... for example,
    # this can fail on Windows if we're running off a share.
    eval {
      require FindBin;
      FindBin->import();
      unshift @INC, "$FindBin::Bin/perllib";
      my $dummy=$FindBin::Bin; # kill used only once warning
    };
    warn $@ if $@;
  }
  if (defined $ENV{CFX_LOCAL_PERLLIB}) {
     unshift @INC, $ENV{CFX_LOCAL_PERLLIB};
  }

}

use CFX5::Init;
CFX5::Init::init();

use vars qw($CVSVersion);
sub BEGIN {
  $CVSVersion='@(#) $Id$\n';
}

use strict;

use CFX5::Output qw(:all);
use CFX5::Config qw(%Config export_conf);
use CFX5::PrintConfig;

use CFX5::CmdLine qw(:util parse_cmdline);

use CFX5::Commands qw(bg_cmd do_cmd_quiet handle_rv);

#
# read the configuration
#
CFX5::Config::read_config();

#
# Parse the command line
#
use vars qw($wait @cmd $first);

@cmd = parse_cmdline
  (\@ARGV,
   'ALLOW_NON_OPTION',
   -NoConsole     => \&handle_std_arg,
   -wait          => \$wait,
   -h             => \&handle_std_arg,
   -help          => '-h',
   -v             => \&handle_std_arg,
   '*'            => sub { $CFX5::CmdLine::Break=1; $first=$_[1]; },
  );

unshift @cmd,$first if defined $first;

if ($wait) {
  my $rv=handle_rv(do_cmd_quiet(@cmd));

  if (!defined $rv) {
    1;
  } elsif ($rv) {
    _error(join(" ",@cmd)," returned exit status $rv");
  }
  exit (defined $rv ? $rv : 2);
} else {
  if ($Config{windows_nt}) {
    # if we're running without a console, stdout and stderr will be
    # pointing to a file.  This is not good!  We close them, so the
    # command can re-open them if it wants ...
    if (!CFX5::Output::have_console()) {
      close STDIN;
      close STDOUT;
      close STDERR;
    }
    exec(@cmd) or
      _error("Unable to run ",join(" ",@cmd));
  } else {
    bg_cmd(@cmd);
  }
}

exit(0);
