/* Run a program if there are new messages in maildirs. */
/* This file is under the Gnu General Public License... NO WARRANTY */

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

char *argv0;

int fileshere(char *here) {
	DIR *dir;
	int i = 0;
	
	dir = opendir(here);
	if (!dir) {
		fprintf(stderr, "%s: couldn't opendir '%s'.\n", argv0, here);
		return 0;
	}

	while (readdir(dir)) i++;

	closedir(dir);

	return i;
}

int main(int argc, char **argv) {
	char buf[1024];
	int i;

	argv0 = argv[0];
	
	if (argc < 3) {
		fprintf(stderr, "usage: %s <program> <maildir> [maildir...]\n",
		       argv[0]);
		exit(-1);
	}

	for (i = 2; i < argc; i++) {
		snprintf(buf, 1024, "%s/new/", argv[i]);

		if (fileshere(buf) > 2) {
			snprintf(buf, 1024, "%s %s", argv[1], argv[i]);
			system(buf);
		}
	}

	exit(0);
}
