/*
 * Mail check routines. Based on EPIC's mail check
 */


#include "irc.h"
#include "mail.h"
#include "lastlog.h"
#include "hook.h"
#include "vars.h"
#include "ircaux.h"
#include "output.h"
#include "window.h"
#include "status.h"
#include "misc.h"
#include <sys/stat.h>

static	char	*mail_path = NULL;

/*
 * check_mail_status: returns 0 if mail status has not changed, 1 if mail
 * status has changed 
 */
int check_mail_status(void)
{
static time_t old_stat = 0;
struct stat stat_buf;
        
	if (!get_int_var(MAIL_VAR))
	{
		old_stat = 0;
		return (0);
	}
	
	if (!mail_path)
	{
		char *tmp_mail_path;
		if ((tmp_mail_path = getenv("MAIL")) != NULL)
			mail_path = m_strdup(tmp_mail_path);
		else
			mail_path = m_3dup(UNIX_MAIL, "/", username);
	}

	if (stat(mail_path, &stat_buf) == -1)
		return 0;

	if (stat_buf.st_ctime > old_stat)
	{
		old_stat = stat_buf.st_ctime;
		if (stat_buf.st_size)
			return 2;
	}
	if (stat_buf.st_size)
		return 1;
		
	return 0;
}

/*
 * check_mail: This here thing counts up the number of pieces of mail and
 * returns it as static string.  If there are no mail messages, null is
 * returned. 
 */

char	*check_mail _((void))
{
static 	int old_count = 0;
static	char ret_str[12];
static  int	i = 0;
	switch (get_int_var(MAIL_VAR))
	{
		case 0:
			return NULL;
		case 1:
		{
			char this[] = "\\|/-";
			switch(check_mail_status())
			{
				case 2:
					if (do_hook(MAIL_LIST, "%s %s", "Mail", "Yes"))
						put_it("%s", convert_output_format(fget_string_var(FORMAT_MAIL_FSET), "%s %s %s", update_clock(GET_TIME), "Mail", "Yes"));
					if (i == 4)
						i = 0;
					sprintf(ret_str, "%c", this[i++]);
				case 1:
					if (!*ret_str)
						return NULL;
					return ret_str;
				case 0:
					i = 0;
					return NULL;
			}
		}
		case 2:
		{
			FILE *mail;
			char buffer[255];
			register int count = 0;

			switch(check_mail_status())
			{

				case 0:
					old_count = 0;
					return NULL;
				case 2:
				{
					if (!(mail = fopen(mail_path, "r")))
						return NULL;

					while (fgets(buffer, 254, mail))
						if (!strncmp("From ", buffer, 5))
							count++;

					fclose(mail);
	
					if (count > old_count)
					{
						if (do_hook(MAIL_LIST, "%d %d", count - old_count, count))
						{
							int lastlog_level = set_lastlog_msg_level(LOG_CRAP);
							say("You have new email.");
							set_lastlog_msg_level(lastlog_level);
						}
					}
	
					old_count = count;
					sprintf(ret_str, "%d", old_count);
				}
				case 1:
					if (*ret_str)
						return ret_str;
			}
		}
	}
	return NULL;
}
