#!/usr/pkg/bin/perl

=begin metadata

Name: env
Description: run a program in a modified environment
Author: Matthew Bafford, dragons@scescape.net
License: perl

=end metadata

=cut


# Perl version of the env command.
# Matthew Bafford
# 2/28/1999

use strict;

use File::Basename qw(basename);

my $Program = basename($0);

while ( @ARGV && $ARGV[0] =~ /^-/ ) {
	my $arg = shift;

	if ( $arg eq '-i' ) {
		%ENV = ();
	} elsif ( $arg =~ /^-u(.*)/ ) {
		my $val = length $1 ? $1 : shift;
		if ($val =~ m/=/) {
			warn "$Program: bad unset argument: '$val'\n";
			exit 2;
		}
		delete $ENV{$val};
	} elsif ($arg eq '--') {
		last;
	} else {
		require Pod::Usage;
		Pod::Usage::pod2usage({ -exitval => 2, -verbose => 0 });
	}
}

while ( @ARGV && $ARGV[0] =~ /=/ ) {
	my ( $name, $value ) = split /=/, shift, 2;

	$ENV{$name} = $value;
}

if ( !@ARGV ) {
	for ( keys %ENV ) {
		print "$_=$ENV{$_}\n";
	}
	exit 0;
}

my $cmd = $ARGV[0];
unless (exec {$cmd} @ARGV) {
	warn "$Program: failed to exec '$cmd': $!\n";
	exit 127;
}

__END__

=pod

=head1 NAME

env - Run a program in a modified environment

=head1 SYNOPSIS

env [B<-i>] [B<-u> name]... [name=value]... [command [args]...]

=head1 DESCRIPTION

I<env> runs a command with the environment modified as specified
by the command line.  If no command is specified, I<env> prints
out the modified environment.

=head2 OPTIONS

I<env> accepts the following options:

=over 4

=item B<-i>

Clears the environment, passing only the values specified to the command.

=item B<-u> I<name>

Clears the environment variable I<name> if it exists.
The value must not include the '=' character.
This option may be repeated.

=back

=head1 DIAGNOSTICS

If the command is invoked, the exit status of I<env> will be the exit
status of the command.  Otherwise, I<env> will return one of the following
values:

    0          env completed successfully.
    1-125      An error occurred in env.
    127        There was an error running the command specified.

=head1 BUGS

I<env> has no known bugs.

=head1 AUTHOR

This Perl version of I<env> was written by
Matthew Bafford, I<dragons@scescape.net>.

=head1 COPYRIGHT and LICENSE

This program is copyright (c) Matthew Bafford 1999.

This program is free and open software.  You may use, modify, distribute,
and sell this program (and any modified variants) in any way you wish,
provided you do not restrict others from doing the same.


