/*
 * Copyright (C)  1998, 1999  Heinz Mauelshagen, Sistina Software
 *
 * February 2000
 *
 * This LVM library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This LVM library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this LVM library; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
 * MA 02111-1307, USA
 *
 */

#include <liblvm.h>


int lvm_remove_recursive ( const char *dir) {
   int ret = 0;
   char *file_name = NULL;
   struct stat sb;
   struct dirent *dir_ent = NULL;
   DIR *this_dir = NULL;

#ifdef DEBUG
   debug_enter ( "lvm_remove_recursive -- CALLED with dir: %s\n", dir);
#endif
   if ( dir != NULL) {
      if ( lstat ( dir, &sb) == 0) {
         /* check beeing called with a file name */
         if (  !S_ISDIR ( sb.st_mode)) unlink ( dir);
         else {
            /* open and read the directory */
            if ( ( this_dir = opendir ( dir)) != NULL) {
               while ( ( dir_ent = readdir ( this_dir)) != NULL && ret == 0) {
                  if ( strcmp ( dir_ent->d_name,".") == 0 ||
                       strcmp ( dir_ent->d_name,"..") == 0) continue;
                  if ( ( file_name = malloc ( strlen (dir) +
                                              strlen (dir_ent->d_name) +
                                              3)) == NULL) {
                     ret = -LVM_EREMOVE_RECURSIVE_MALLOC;
                     goto lvm_remove_recursive_end;
                  }
                  sprintf ( file_name, "%s/%s%c", dir, dir_ent->d_name, 0);
                  if ( lstat ( file_name, &sb) == 0) {
                     if ( S_ISDIR ( sb.st_mode)) {
                         if ( ( ret = lvm_remove_recursive ( file_name)) == 0)
                            rmdir ( file_name);
                     } else unlink ( file_name);
                  }
                  free ( file_name);
               }
               closedir ( this_dir);
               rmdir ( dir);
            } else ret = -LVM_EREMOVE_RECURSIVE_OPENDIR;
         }
      }
   }

lvm_remove_recursive_end:
#ifdef DEBUG
   debug_leave ( "lvm_remove_recursive -- LEAVING with ret: %d\n", ret);
#endif
   return ret;
}
