/*
** bwiz.c - This is the Birthday Wizard.
**	  - This is part of the finger distribution.
**
** Run once every morning to brighten a users
** birthday up.
**
** On SCO Xenix, I created a user, "bwiz" that crons this program at
** 00:05 in the morning.
**
** Written by Keith Gabryelski
** Released into public domain September 1, 1988.
** Please keep this header.
*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/dir.h>
#include <fcntl.h>
#include <a.out.h>
#include "defs.h"
#include "finger.h"

extern int errno;
extern char *ctime(), *strtok();

char
    *progname,
    *whois_dbase_dir = WHOIS_DBASE_DIR;

main(argc, argv)
int argc;
char **argv;
{
    char *timestr;
    int fd;
    long tloc;
    struct direct dir;

    progname = *argv++; --argc;

    
    tloc = time((long *)0);
    timestr = ctime(&tloc);
    timestr[sizeof("DAY MON DD")-1] = '\0';
    timestr += (sizeof("DAY ") - 1);		/* - 1 for '\0'. */

#ifdef DEBUG
    printf("timestr = `%s'.\n", timestr);
#endif						/* DEBUG */

    if ((fd = open(whois_dbase_dir, O_RDONLY)) < 0)
	fprintf(stderr,	"%s: Couldn't find database directory %s (%s).\n",
		progname, whois_dbase_dir, puterr(errno));
    else
	while (read(fd, &dir, sizeof(struct direct)) == sizeof(struct direct))
	    if (strcmp(dir.d_name, ".") && strcmp(dir.d_name, "..") &&
		is_birthday(dir.d_name, timestr))
		send_birthday_card(dir.d_name);

}

/*
** Return TRUE if it is NAME's birthday is on THE_DATE.
*/

is_birthday(name, the_date)
char *name, *the_date;
{
    char *ptr, our_bday[sizeof("MMM DD")];
    int is_bday = FALSE;
    struct finger f;

    strncpy(f.uname, name, sizeof(f.uname));
    get_dbase_info(&f);

    if (f.valid_whois)
    {
	if ((ptr = strtok(f.birthday, " ")) != NULL)
	{
	    sprintf(our_bday, "%.3s %2d", ptr, atoi(strtok(NULL, " ")));
#ifdef DEBUG
	    printf("name = %s, our_bday = %s.\n", name, our_bday);
#endif /* DEBUG */
	    if (!strcmp(our_bday, the_date))
		is_bday = TRUE;
	}
    }

    return is_bday;
}

/*
** Send a birthday card to NAME.
*/
send_birthday_card(name)
char *name;
{
    FILE *fp;

    if ((fp = freopen(BIRTHDAY_CARD, "r", stdin)) == (FILE *)NULL)
    {
	fprintf(stderr, "%s: could reopen stdin (%s).\n", progname,
		puterr(errno));
	exit(-1);
    }

    execl(MAILER, MAILER, name, NULL);

    fprintf(stderr, "%s: Couldn't exec %s (%s).\n", progname, MAILER,
	    puterr(errno));
    exit(-1);
}
