/*
 * dirwatch.c
 *
 * (c) 2002 Jos Backus
 *
 * 2002-05-24 jos Initial version
 * 2002-09-16 jos Added sleep() hack to make maildirsmtp see new mail
 *
 */

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <err.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <sys/wait.h>

void
usage(void)
{
    errx(64, "usage: %s directory command [...]", getprogname());
}

int
main(int argc, char *argv[])
{
    int kq;
    int fd, n;
    char *d;
    struct kevent ev;

    --argc; ++argv;
    if (argc < 2)
	usage();
    d = *argv;
    --argc; ++argv;

    if ((kq = kqueue()) < 0)
	err(1, "kqueue() failed");

    if ((fd = open(d, O_RDONLY | O_NONBLOCK)) < 0)
	err(1, "open(%s) failed", d);
	
    /* Register */
    EV_SET(&ev, fd, EVFILT_VNODE, EV_ADD | EV_ENABLE | EV_CLEAR, NOTE_WRITE,
	0, 0);
    if (kevent(kq, &ev, 1, NULL, 0, NULL) < 0)
	err(1, "kevent() registration failed");

    /* Poll */
    for (;;)
	if ((n = kevent(kq, NULL, 0, &ev, 1, NULL)) == 1) {
	    pid_t kid;
	    int status;
	    switch (kid = fork()) {
		case 0:
		    sleep(1);
		    execvp(*argv, argv);
		    err(1, "execvp(%s) failed", *argv);
		    break;
		case -1:
		    err(1, "fork() failed");
		    break;
		default:
		    waitpid(kid, &status, 0);
		    break;
	    }
	} else
	    err(1, "kevent() poll failed");

    exit(0);
}

