#!/usr/bin/perl -w
#---------#---------#---------#---------#---------#---------#---------#---------
#
# Date:         19 Oct 00
# Title:        create all missing directories in a path
# Creator:      larg
# Description:
#   the script takes a directory path
#   if the existing path is incomplete, the missing dirs are created.
# Modifications:
#
#---------#---------#---------#---------#---------#---------#---------#---------


# check the command line options (using a perl standard library)
   use Getopt::Long;
   # options (values are inserted into the variables $opt_...)
   # path - the directory path to create if missing
   $opt_path = undef;
   my $provided = GetOptions( "path=s" );
   unless ($provided and defined $opt_path) {
      print "usage: \n   $0 --path <dir/dir/dir> \n\n";
      exit;
   }

# more checks
   if ( -d $opt_path ) {
      print "\nThe path $opt_path already exists. \n\n";
      exit;
   }

# get busy
   use File::Basename;
   my @created = &make_path( $opt_path );

   print " \n"; # missing from some sub error prints below.
   if ( scalar @created == 0 ) {
      print "no directories were created. \n";
   } else {
      print "created these directories: \n";
      foreach (@created) {print "   $_ \n";};
   }
   print " \n"; # for super neatness

#---------#---------#---------#---------#---------#---------#---------#---------
#
sub make_path {
  my ($path) = @_; # a path string eg. dir01/dir02/dir03
   my @created; # list of directories that are made by this sub

   my $mode = 0777; # the first character MUST be the number mode
   # see "perldoc -f chmod"

# if the parent directory does not exist,
# recurse this sub with the parent dir
   my $parent = File::Basename::dirname($path);
   push (@created, &make_path($parent)) unless (-d $parent);

# create the directory
   if ( mkdir("$path", $mode) ) {
      push(@created, $path);
   } else {
      my $e = $!;
      print STDERR "cannot create $path: $e \n";
   }

   @created;
}

