/*
 *  hap -- a mail notification program
 * 
 *  copyright 1995 by Eric Fischer, etaoin@uchicago.edu
 * 
 *  copies of hap may be redistributed under the terms of the
 *  GNU public license, copies of which are available from
 *  the Free Software Foundation, 59 Temple Place, Boston, MA
 *  02111 USA.
 *
 */

#include "hap.h"

/* get the new mh-style messages, if any, in "each".  This will be
   catted to the end of whattoprint if there's already something there.
*/

char *
mhnotice(each, whattoprint)
	mailbox *each;
	char *whattoprint;
{
	flist *newlist;
	flist *check;
	time_t now;

	now = getmtime(each->name);
	if (now != each->mtime) {
		newlist = lookdir(each->name);
		check = diffdir(each->isdir, newlist);

		if (check) {
			flist *it = check;

			while (it) {
				char *eep = readmh(each->name, it->name);

				if (eep) {
					if (fileannounce) {
						if (lastadd != each->name) {
							addstr(&whattoprint, 
							    "New mail in ");
							addstr(&whattoprint, 
							    each->name);
							addstr(&whattoprint, 
							    ":\n");

							lastadd = each->name;
						}
					}
					addstr(&whattoprint, eep);
				}
				it = it->next;
			}
		}
		each->mtime = now;
		freelist(each->isdir);
		each->isdir = newlist;
		freelist(check);
	}
	return whattoprint;
}

/* get the new messages in a regular file.  the list will be
   added to the end of whattoprint.
*/

char *
filenotice(each, whattoprint)
	mailbox *each;
	char *whattoprint;
{
	long size = getsize(each->name);

    /* if size has changed, wait for it to stabilize.
       if it's the same but not stable, we'll catch
       it next time around.
     */

	if (size != each->size) {
		long sizenow = size;

	    /* keep looping until we get the same
	       size twice in a row
	     */

		while (1) {
			sleep(1);

			size = getsize(each->name);
			if (size == sizenow)
				break;
			sizenow = size;
		}
	}

	if (size > each->size) {
		char *goo = getmessages(*each, each->size);

		if (goo) {
			if (fileannounce && (lastadd != each->name)) {
				addstr(&whattoprint, "New mail in ");
				addstr(&whattoprint, each->name);

				if (each->size > 0) {
					addstr(&whattoprint, ": (was ");
					addstr(&whattoprint, ftoa
					       (each->size / 1024.0));
					addstr(&whattoprint, "k)\n");
				} else {
					addstr(&whattoprint, ":\n");
				}

				lastadd = each->name;
			}

			addstr(&whattoprint, goo);
		}
	}

	each->size = size;
	return whattoprint;
}
