#!/usr/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 dirname);
use Getopt::Std qw(getopts);

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

my ($VERSION) = '1.2';
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) {
    unless (-d $directory) {
        warn "$Program: '$directory': not a directory or does not exist\n";
        $rc = EX_FAILURE;
        next;
    }
    unless (rmdir $directory) {
        warn "$Program: failed to remove '$directory': $!\n";
        $rc = EX_FAILURE;
        next;
    };
    if ($opt{'p'}) {
        # Errors are ignored once in recursion.
        while (1) {
            $directory = dirname($directory);
            last if ($directory eq '.' || $directory eq '/');

            unless (rmdir $directory) {
                warn "$Program: failed to remove '$directory': $!\n";
                $rc = EX_FAILURE;
                last;
            }
        }
    }
}
exit $rc;

__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

