/* rmrf.c:
 *
 * vim:smartindent ts=8:sts=2:sta:et:ai:shiftwidth=2
 ****************************************************************
 * Copyright (C) 2003 Tom Lord
 *
 * See the file "COPYING" for further information about
 * the copyright and warranty status of this work.
 */


#include "hackerlab/bugs/exception.h"
#include "hackerlab/os/errno.h"
#include "hackerlab/os/errno-to-string.h"
#include "hackerlab/char/str.h"
#include "hackerlab/fs/file-names.h"
#include "hackerlab/vu/safe.h"
#include "libfsutils/dir-listing.h"
#include "libfsutils/rmrf.h"



void
rmrf_file (t_uchar * path)
{
  int errn;
  struct stat stat_buf;

  if (vu_lstat (&errn, path, &stat_buf))
    {
      if (errn == ENOENT)
        return;
      else
        {
          safe_printfmt (2, "rmrf_file: I/O error (%s) from lstat for %s\n", errno_to_string (errn), path);
          exit (2);
        }
    }


  if (!S_ISDIR (stat_buf.st_mode))
    {
      safe_unlink (path);
    }
  else
    {
      rel_table contents;
      int lim;
      int x;

      contents = directory_files (path);

      lim = rel_n_records (contents);
      for (x = 0; x < lim; ++x)
        {
          t_uchar * sub_path;

          if (!str_cmp (".", contents[x][0]))
            continue;
          if (!str_cmp ("..", contents[x][0]))
            continue;

          sub_path = file_name_in_vicinity (0, path, contents[x][0]);
          rmrf_file (sub_path);
          lim_free (0, sub_path);
        }

      rel_free_table (contents);
      safe_rmdir (path);
    }
}

/**
 * \brief talloc destructor for strings
 */
int
rmrf_on_free (void * data)
{
  struct exception * e;
  /* Throwing past talloc is not a good idea
   * until we have audited it for exception
   * throwing safety
   */
  Try
    {
      rmrf_file (data);
    }
  Catch (e)
    {
      talloc_free (e);
      /* XXX debug might be reasonable here */
      /* don't return -1 - this memory should not be freed again.
       * -- its gone
       * RobertCollins 20050511
       */
    }
  return 0;
}



/* tag: Tom Lord Tue May 13 16:29:13 2003 (rmrf.c)
 */


syntax highlighted by Code2HTML, v. 0.9.1