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

#include "globals.h"
#include "mh.h"

int count_mh( struct mbox_struct * mb ) {
        DIR           *dir        = NULL;
	FILE          *f          = NULL;
	char           line[MAX_INPUT_LENGTH+1]  = "";
	char           fname[MAX_INPUT_LENGTH+1] = "";
	int            ctotal     = 0;
	int            cnew       = 0;
	struct dirent *dir_entry  = NULL;

	/* Open the mH directory */
	if ((dir = opendir(mb->file)) == NULL) 
	        return(-1);

	/* Parse through each file in the directory */
	while ((dir_entry = readdir(dir)) != NULL) {
	        /* Ignore files that are not mH mail files */
	        if (dir_entry->d_name[0] != '.' && dir_entry->d_name[0] != ',') {
		        strcpy(fname, mb->file);
			/* Make sure the directory name ends in a slash. */
			if (fname[strlen(fname) - 1] != '/')
			        strncat(fname, "/",
					MAX_INPUT_LENGTH - strlen(fname));
		        strncat(fname, dir_entry->d_name,
				MAX_INPUT_LENGTH - strlen(fname));
		        fname[MAX_INPUT_LENGTH] = '\0';

			if ( (f = fopen(fname, "r")) == NULL ) {
			        return(-1);
			}
			
			++ctotal;
			++cnew;

			while ( fgets(line, MAX_INPUT_LENGTH, f) ) {
			        switch (line[0]) {		   
				case 'S':
				        if ( !strncmp(line, "Status: ", 8) ) {
					      if (mb->flags & FLAG_UNREAD_AS_NEW) {
						      if (!strncmp(line, "Status: RO", 10))
							      --cnew;
					      } else if (!strncmp(line, "Status: R", 9)) {
						      --cnew; 
					      }
					      /* Once we find the Status header, no need
						 to keep reading from this file. */
					      goto close;
					}
					break;
				}			
			}
		close:
			fclose(f);
		}
	}
	
	if ( (mb->cnew != cnew) && (cnew != 0) ) {
	        pthread_mutex_lock(&mb->mutex);
		mb->flags |= FLAG_ARRIVED;
		pthread_mutex_unlock(&mb->mutex);
	}

	mb->ctotal = ctotal;
	mb->cnew = cnew;
	
	return(0);
}

void mh_handle( struct mbox_struct * mb ) {
	/* Since we never really intend to quit this function,
	 * all "global" stuff may go on the stack here */

	if ( ! strlen(mb->file) ) {
		printf("asmail: mh_handle: no mailbox directory specified.\n");
		mb->status = STAT_FAIL;
		signal_update();
		pthread_exit(NULL);
	}
	if ( strlen(mb->file) > (MAX_INPUT_LENGTH-4)) {
		printf("asmail: mh_handle: mailbox directory name is too long.\n");
		mb->status = STAT_FAIL;
		signal_update();
		pthread_exit(NULL);
	}

	while (1) {
		mb->status |= STAT_RUN;
		signal_update();
		
		if ( count_mh( mb ) < 0 ) {
			mb->status = STAT_FAIL;
			signal_update();
		} else {
		        if ( mb->cnew > 0 ) {
				mb->mail = MAIL_NEW;
				pthread_mutex_lock(&mb->mutex);
				mb->flags |= FLAG_ARRIVED;
				pthread_mutex_unlock(&mb->mutex);
			}
			else if ( mb->ctotal ) {
				mb->mail = MAIL_OLD;
			}
			else {
				mb->mail = MAIL_NONE;
			}
		}

		if ( mb->status == STAT_RUN ) 
		        mb->status = STAT_IDLE;
	
		signal_update();
		sleep_check(mb->update);
	}
}
