/*
  DirAge
  
  Reports oldest and newest files (modification)
  in a directory tree.

  (C) Kai Engert 2002
*/


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

time_t oldest_ts = INT_MAX;
time_t newest_ts = 0;

char oldest_name[NAME_MAX+1] = {0};
char newest_name[NAME_MAX+1] = {0};


void searchdir(const char *pathname)
{
  DIR *directory = NULL;
  struct dirent *direntry = NULL;
  struct stat fileinfo;
  char my_path[PATH_MAX+1] = {0};
  int my_path_len = 0;
  char a_path[PATH_MAX+1] = {0};
  char *filename_part_pointer = 0;

  printf(".");
  fflush(stdout);

  strcpy(my_path, pathname);
  strcat(my_path, "/");
  my_path_len = strlen(my_path);

  strcpy(a_path, my_path);
  filename_part_pointer = a_path + my_path_len;
  
  directory = opendir(my_path);
  if (!directory)
    return;

  while (direntry = readdir(directory)) {
    if (!direntry->d_reclen)
      continue;

    strcpy(filename_part_pointer, direntry->d_name);
    
    if (!stat(a_path, &fileinfo)) {
      if (S_ISREG(fileinfo.st_mode)) {
        if (fileinfo.st_mtime > newest_ts) {
          newest_ts = fileinfo.st_mtime;
          strcpy(newest_name, a_path);
        }
        if (fileinfo.st_mtime < oldest_ts) {
          oldest_ts = fileinfo.st_mtime;
          strcpy(oldest_name, a_path);
        }
      }
      else if( S_ISDIR(fileinfo.st_mode)) {
        if (0 != strcmp(direntry->d_name, ".")
            && 0 != strcmp(direntry->d_name, ".."))  {
          searchdir(a_path);
        }
      }
    }
  }
}

int main(int argc, char *argv[])
{
  if (argc != 2)
    return -1;

  printf("Searching directory\n  %s\nfor files with oldest and newest modification dates.\n"
    "Please wait", argv[1]);

  searchdir(argv[1]);
  
  printf("\nOldest file: %s\nNewest file: %s\n", oldest_name, newest_name);

  return 0;
}

