/********************************************************
 * File: jbdir.c
 * Created at Sun Jan 28 22:10:25 MSK 2001 by raorn // raorn@binec.ru
 * Directory reading stuff
 * $Id: jbdir.c,v 1.6 2002/02/10 23:36:59 raorn Exp $
 *******************************************************/
#include <machine/defs.h>

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#ifdef HAVE_DIRENT_H
# include <dirent.h>
#else
# define dirent direct
# ifdef HAVE_SYS_NDIR_H
#  include <sys/ndir.h>
# endif
# ifdef HAVE_SYS_DIR_H
#  include <sys/dir.h>
# endif
# ifdef HAVE_NDIR_H
#  include <ndir.h>
# endif
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif

#include "jblist.h"
#include "mystrncpy.h"
#include "path.h"

#include "jbdir.h"

bool ReadDir(uchar * dirname, struct jbList *filelist, bool(*acceptfunc) (uchar * filename))
{
  DIR *dir;
  struct dirent *dirent;
  struct FileEntry *tmp;
  char buf[200];

  jbNewList(filelist);

  if (!(dir = opendir(dirname)))
    return (FALSE);

  while ((dirent = readdir(dir))) {
    bool add;

    if (!acceptfunc)
      add = TRUE;
    else
      add = (*acceptfunc) (dirent->d_name);

    MakeFullPath(dirname, dirent->d_name, buf, 200);

#ifdef __MINGW32__
    if (add) {
      int hdl;
      struct _finddata_t ffblk;

      hdl = _findfirst(buf,&ffblk);
      if(ffblk.attrib&_A_HIDDEN)
        add = FALSE;

      _findclose(hdl);
    }
#endif /* __MINGW32__ */

    if (add) {
      struct stat st;

      if (stat(buf, &st) == 0) {
        if (!(tmp=(struct FileEntry *) calloc(1, sizeof(struct FileEntry)))) {
          jbFreeList(filelist);
          closedir(dir);
          return (FALSE);
        }

        mystrncpy(tmp->Name, dirent->d_name, 100);
        tmp->Size = st.st_size;
        tmp->Date = st.st_mtime;

        jbAddNode(filelist, (struct jbNode *) tmp);
      }
    }
  }

  closedir(dir);

  return (TRUE);
}

bool ScanDir(uchar * dirname, void (*func) (uchar * file))
{
  DIR *dir;
  struct dirent *dirent;

  if (!(dir = opendir(dirname)))
    return (FALSE);

  while ((dirent = readdir(dir)))
    (*func) (dirent->d_name);

  closedir(dir);

  return (TRUE);
}

struct FileEntry *GetFileEntry(uchar * file)
{
  struct stat st;
  struct FileEntry *tmp;

  if (stat(file, &st) != 0)
    return (FALSE);

  if (!(tmp=(struct FileEntry *) calloc(1, sizeof(struct FileEntry))))
    return (FALSE);

  mystrncpy(tmp->Name, GetFilePart(file), 100);

  tmp->Size = st.st_size;
  tmp->Date = st.st_mtime;

  return (tmp);
}


syntax highlighted by Code2HTML, v. 0.9.1