/* rmrf.c:
 *
 ****************************************************************
 * Copyright (C) 2003 Tom Lord
 *
 * See the file "COPYING" for further information about
 * the copyright and warranty status of this work.
 */


#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 "tla/libfsutils/dir-listing.h"
#include "tla/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);
    }
}



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