#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
              
#include <dirent.h>

#include "shared_login_logs.h"
#include "shared_util.h"
#include "shared_cs_util.h"


/* sorts list by modification time of 
** file, in reverse order (that is,
** newest files are at the top of the list
**/
static LOGFILE_NODE*
sort_log_filelist (LOGFILE_NODE *head)
{
  LOGFILE_NODE *q, *tail, *p, *r;
  if (head != NULL)
    {
      tail = head;
      while (tail->next)
	{
	  q = tail->next;
	  if (q->buf.st_mtime > head->buf.st_mtime)
	    {
	      tail->next = q->next;
	      q->next = head;
	      head = q;
	    }
	  else
	    {
	      r = head;
	      p = r->next;
	      while (q->buf.st_mtime < p->buf.st_mtime) /* shared_authenticate.c */
		{
		  r = p;
		  p = r->next;
		}
	      if (q == p)
		tail = q;
	      else
		{
		  tail->next = q->next;
		  q->next = p;
		  r->next = q;
		}
	    }
	}
    }
    return  head;
}







LOGFILE_NODE * 
build_logfile_list(int *count, const char *path, const char *filter)
{
  LOGFILE_NODE *head =0, *new_node, *ptr; 
  DIR *dir_p;
  struct dirent *dir_entry;
  char logfile[MAX_PATH +1];
  struct stat buf;

  *count = 0;
  dir_p = opendir(path);
  if(!dir_p)
      cs_critical_error(ERR_OPENDIR_FAILED, path);
  
  while((dir_entry=readdir(dir_p)) != NULL)
    {
     if(strstr(dir_entry->d_name, filter))
      {
       snprintf(logfile, MAX_PATH + 1, "%s/%s", path, dir_entry->d_name); 
       if(!stat(logfile, &buf))
        {
          new_node = (LOGFILE_NODE *)malloc(sizeof(LOGFILE_NODE));
          if(!new_node)
                cs_critical_error(ERR_MALLOC_FAILED, "");
          strncpy(new_node->filename, dir_entry->d_name, MAX_PATH +1);
          new_node->buf = buf;
	  new_node->next = 0;
	  
	  if(!head)
	    {
	      head = new_node;
 	    }  
 	  else
	    {
	      for(ptr=head; ptr->next; ptr=ptr->next);
	      ptr->next = new_node;
	    }  
          *count = *count + 1;	  
        }  /* if we can stat the file */ 
      }   /* if name doesn't start with a dot */
    }    /* while more dir entries to read */
   closedir(dir_p);    
   return sort_log_filelist(head);   
}           







void free_logfile_list(LOGFILE_NODE *head)
{
 LOGFILE_NODE *ptr;
 
  while(head)
   {
    ptr = head;
    head = head -> next;
    free(ptr);
   }
}    

