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

char * polaczNapisy(char * a, char * b)
{
        char * c;
        unsigned int size = 0;

        size = sizeof(char) * (strlen(a) + strlen(b) + 2);
        c = malloc(size);
        bzero(c, size);
        snprintf(c, size, "%s/%s", a, b);
        return c;
}

void usageAndExit(void)
{
	printf("biff1 [-s TIME] [-p LOGIN]\n\nTIME\t- pause in seconds between checks of mailbox\nLOGIN\t- name of mailbox to check\n");
	exit(1);
}

int main(int argc, char ** argv) {
	struct stat statBuf;
	time_t rozmiar;
	char * mailFile;
	unsigned int sleepTime = 1;
	char c;

	if (getenv("MAILSLEEP") != NULL) sleepTime = atoi(getenv("MAILSLEEP"));
	mailFile = polaczNapisy("/var/spool/mail", getlogin());

	stat(mailFile, &statBuf);

	while((c = getopt(argc, argv, "s:p:")) != -1)
	{
		switch (c)
		{
			case 's':
				sleepTime = atoi(optarg);
				break;
			case 'p':
				mailFile = polaczNapisy("/var/spool/mail", optarg);
				break;
			default:
				usageAndExit();
				break;
		}
	}

	printf("MAILBOX: %s\nTIME: %i\n", mailFile, sleepTime);
	rozmiar = statBuf.st_size;
	for( ; ; )
	{
		stat(mailFile, &statBuf);
		if (statBuf.st_size > rozmiar)
		{
			printf("%s", "You have new mail.\n");
		}
		rozmiar = statBuf.st_size;
		sleep(sleepTime);
	}
}
