/*
   Newmail version 2                    Jeroen Berger November 1993
   
   Checks mailbox of user and informs him/her of receiving new mail.
   Looks for environment-variable "mail" for specification for
   newmail check-interval (in seconds).

   Puts itself in the background after starting up.
   Automatically exits itself when the user proces that invoked 
   newmail does exit.

   Any questions or suggestions about this program can be send to:
   
   berger@tudebg.et.tudelft.nl or
   lemmens@dv.twi.tudelft.nl
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <stat.h>
#include <signal.h>

#define		FALSE		0
#define		TRUE		1

void DaemonMode(void)
{		
	switch ((int)fork())
	{	case -1:
			fputs("can't fork newmail !\n",stderr);
			exit(1);
			break;
		case 0:
			(void)setpgid(0,0);
			(void)kill(getppid(),SIGKILL);
			break;
		default:
			/* parent waits to be killed */
			exit(0);
			break;
	}
}

void main( void )
{
	/* MailPath must be \\ instead of / or else standard
	 I/O functions can't handle this path ! (KL)
	*/
	
	char			achMailFile[40], achMailPath[]={ "u:\\usr\\mail\\" };
	char			achNewMailMessage[]={"\7\r\nYou have new mail.\7"};
	char			achErrorMessage[]={"\7\r\nCan't handle your mail-file (anymore).\7"};
	char			chStartUp=TRUE;
	struct stat 	FileStat;
	unsigned		usSleep=60;
	FILE			*pFp;
	size_t			LastSize=0;
	int				ppid=getppid();	/* pid of starting shell */
	
	signal(SIGTTOU,SIG_IGN);
	
	if( getenv( "mail" )!=NULL )
	{	/* changed sscanf into atoi, to make .ttp smaller (KL) */
		usSleep = atoi(getenv( "mail" ) );
	}
	
	if( getenv( "LOGNAME" )==NULL )
	{
		fputs( "\nNo logname specified!\n", stderr );
		exit( 1 );
	}
	
	DaemonMode();	/* added this (KL) */
	
	/* changed sprint into str functions to make .ttp smaller (KL) */
	strcpy(achMailFile, achMailPath);
	strcat(achMailFile, getenv( "LOGNAME" ) );
	
	do
	{
		if( stat( achMailFile, &FileStat )!=0 )
		{
			if((pFp=fopen( achMailFile, "w" )) != NULL)
				fclose( pFp );

			/* I moved this part here, to save system load (KL) */			
			if( stat( achMailFile, &FileStat )!=0 )
			{
				fputs( achErrorMessage, stderr );
				exit( 0 );
			}
		}

		/* added ==FALSE or else it won't work if you alter
		   the values for FALSE and TRUE !! (KL)
		*/
		if( ( FileStat.st_size>LastSize ) && chStartUp==FALSE )
			puts( achNewMailMessage );
		
		chStartUp=FALSE;
		LastSize=FileStat.st_size;
		
		sleep( usSleep );
	}
	while( kill(ppid,SIGNULL) == 0);	/* as long as starting shel runs */
}