/*
 * A qmail directory checker for xbiff.  Just gets the time the last
 * file was written, and stashes that in the directory.
 */


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

/* xbiff return values */
#define	NEWMAIL		0
#define NOCHANGE	1
#define CLEARED		2

/* last mail timestamp file */
#define PREVMAIL	".lastmail"
#define RETURN(x)	if (verbose) printf("Returning %x\n", x); return x

int
main(int argc, char **argv) {
  int		verbose = 0, fd ;
  time_t	latest = 0, last ;
  char		*name, *myname ;
  DIR		*dir ;
  struct dirent	*file ;
  struct stat	stat_buff ;

  /* Arguments */
  myname = argv[0] ;
  argv += 1 ;
  argc -= 1 ;
  
  if (argc && **argv == '-') {
    if ((*argv)[1] == 'v') verbose = 1 ;
    argv += 1 ;
    argc -= 1 ;
  }
  
  if (argc) name = *argv ;
  else if (!(name = getenv("MAILDIR"))) {
    if (verbose) fprintf(stderr, "%s: No mail directory specified\n", myname) ;
    RETURN(NOCHANGE) ;
  }

  /* Go to the MailDir in question, the new subdirectory. */
  if ((chdir(name) == -1) || (chdir("new") == -1)) {
    if (verbose) perror(myname) ;
    RETURN(NOCHANGE) ;
  }

  /* Get the update time for the latest file in the directory */
  if (!(dir = opendir("."))) {
    if (verbose) perror(myname) ;
    RETURN(NOCHANGE) ;
  }

  while (file = readdir(dir))
    if (file->d_namlen > 0 && file->d_name[0] != '.') {
      file->d_name[file->d_namlen] = '\0' ;
      if (verbose) fprintf(stderr, "%s: ", file->d_name) ;
      if (stat(file->d_name, &stat_buff) == -1) {
	if (verbose) perror(myname) ;
      }	else {
	if (verbose) fprintf(stderr, "%d\n", stat_buff.st_mtimespec.tv_sec) ;
	if (latest < stat_buff.st_mtimespec.tv_sec)
	  latest = stat_buff.st_mtimespec.tv_sec ;
      }
    }
  if (closedir(dir) && verbose) perror(myname) ;
  if (verbose) fprintf(stderr, "Lastest: %d\n", latest) ;
  
  /* If we didn't see any files, then just clean up and exit */
  if (!latest) {
    unlink(PREVMAIL) ;
    RETURN(CLEARED) ;
  }

  /* Now get the time of the file the last time we checked on it */
  if (!(fd = open(PREVMAIL, O_RDWR | O_CREAT | O_EXLOCK, S_IRUSR | S_IWUSR))) {
    if (verbose) perror(myname) ;
    RETURN(NOCHANGE) ;
  }

  /* Files in the new directory and no prevmail -> new mail! */
  if ((lseek(fd, (off_t) 0, SEEK_SET) == -1) && verbose)
    perror(myname) ;

  if (read(fd, &last, sizeof(last)) != sizeof(last))
    last = 0 ;
  if (verbose) fprintf(stderr, "Last: %d\n", last) ;

  if ((lseek(fd, (off_t) 0, SEEK_SET) == -1) && verbose)
    perror(myname) ;

  if ((write(fd, &latest, sizeof(latest)) != sizeof(latest)) && verbose)
    perror(myname) ;

  if ((close(fd) == -1) && verbose) perror(myname) ;

  RETURN(last < latest ? NEWMAIL : NOCHANGE) ;
  }
