#!/usr/pkg/bin/perl

=begin metadata

Name: rmdir
Description: remove directories
Author: Abigail, perlpowertools@abigail.be
License: perl

=end metadata

=cut


use strict;

use File::Basename qw(basename);
use File::Spec;
use Getopt::Std qw(getopts);

use constant EX_SUCCESS => 0;
use constant EX_FAILURE => 1;

my ($VERSION) = '1.3';
my $Program = basename($0);

my $rc = EX_SUCCESS;
my %opt;
if (!getopts('p', \%opt) || scalar(@ARGV) == 0) {
    warn "usage: $Program [-p] directory ...\n";
    exit EX_FAILURE;
}
foreach my $directory (@ARGV) {
    next unless remove($directory);
    if ($opt{'p'}) {
        my @parts = File::Spec->splitdir($directory);
        my @seq = 0 .. (scalar(@parts) - 2);
        for (reverse @seq) {
            my $d = File::Spec->catfile(@parts[0 .. $_]);
            next if length($d) == 0; # absolute path
            remove($d);
        }
    }
}
exit $rc;

sub remove {
    my $dir = shift;
    unless (rmdir $dir) {
        warn "$Program: failed to remove '$dir': $!\n";
        $rc = EX_FAILURE;
        return 0;
    }
    return 1;
}

__END__

=pod

=head1 NAME

rmdir - remove directories

=head1 SYNOPSIS

    rmdir [-p] directory ...

=head1 DESCRIPTION

I<rmdir> removes the directories which are given as argument, if
they are empty. Trying to remove a non-empty directory is regarded
as an error.

=head2 OPTIONS

I<rmdir> accepts the following options:

=over 4

=item -p

Make I<rmdir> treat the arguments as path names, of which all non-empty
components will be removed. Leftmost components will be removed first.

=back

=head1 ENVIRONMENT

The working of I<rmdir> is not influenced by any environment variables.

=head1 BUGS

I<rmdir> does not have any known bugs.

=head1 STANDARDS

This I<rmdir> implementation is compatible with the B<OpenBSD> implementation,
which is expected to be compatible with the B<IEEE Std1003.2-1992>
(aka B<POSIX.2>) standard.

=head1 AUTHOR

The Perl implementation of I<rmdir> was written by Abigail, I<perlpowertools@abigail.be>.

=head1 COPYRIGHT and LICENSE

This program is copyright by Abigail 1999.

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

=cut

