/* DWF 1998-12-15 */

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
#include <dirent.h>
#include <signal.h>

#define buflen 10000

void
putout (char *s) {
  static char buf[buflen];
  static int first = 1;
  if (s == NULL) {
    printf ("%s\n", buf);
    first = 1;
  } else {
    if (!first)
      printf ("%-40s  \\\n", buf);
    first = 0;
    strcpy (buf, s);
  }
}

void
do_dir (time_t lcut, time_t rcut, char *path) {
  DIR *dirp;
  struct dirent *dp;
  char buf[buflen];
  assert (path);
  assert (path[strlen(path)-1] == '/');
  dirp = opendir(path);
  if (!dirp) { /* opendir failed */
    perror (path);
  } else {
    for (dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
      if ((!strcmp (dp->d_name, ".")) ||
          (!strcmp (dp->d_name, "..")))
        continue;
      else {
        struct stat s;
        sprintf (buf, "%s%s", path, dp->d_name);
        if (stat (buf, &s) == 0) {
          if (s.st_mtime >= lcut && s.st_mtime <= rcut)
            putout (buf);
          if (S_ISDIR (s.st_mode)) {
            /* Recurse directory */
            strcat (buf, "/");
            do_dir (lcut, rcut, buf);
          }
        } else { /* stat failed */
	  perror (buf); // stat failed
        }
      }
    }
    closedir(dirp);
  }
}

time_t
parsets (char *ts) {
  struct tm temp_tm;
  time_t posixtime;
  temp_tm.tm_sec = 0;
  assert (sscanf (ts, "%u-%u-%u %u:%u",
    &(temp_tm.tm_year),
    &(temp_tm.tm_mon),
    &(temp_tm.tm_mday),
    &(temp_tm.tm_hour),
    &(temp_tm.tm_min)) == 5);
  temp_tm.tm_year -= 1900;
  temp_tm.tm_mon -= 1;
  temp_tm.tm_isdst = -1;
  assert ((posixtime = mktime (&temp_tm)) != (time_t)(-1));
  return posixtime;
}

int main (int argc, char **argv) {
  time_t lcut, rcut;
  char buf[buflen];
  if (argc != 4) {
    fprintf (stderr, "Usage:  deinstall search-directory begin-timestamp end-timestamp\n");
    fprintf (stderr, "Timestamp should be \"YYYY-MM-DD HH:MM\"\n");
    exit (-1);
  }

  lcut = parsets (argv[2]);
  rcut = parsets (argv[3]);

  strcpy (buf, argv[1]);
  if (buf[strlen(buf)-1] != '/')
    strcat (buf, "/");

  putout ("rm -rf");
  do_dir (lcut, rcut, buf);
  putout (NULL);
  exit (0);
}
