/*
   birthday.c

   Birthday/Anniversary display on login

   (c) 1996 AS Mortimer

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License as
    published by the Free Software Foundation; either version 2 of the
    License, or (at your option) any later version.  You may also
    distribute it under the Artistic License, as comes with Perl.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

    You should also have recieved a copy of the Artistic license with
    this program.

   $Id: bdengine.c,v 1.4 2006/01/10 17:27:53 andymort Exp $
   
   We're getting there. At the moment, the file used by default is ~/.birthdays
   under UNIX, or C:\PERSONAL\BDAYS.LST under DOS, but this can be overridden on
   the command line. The file has the following format:

   name/event/whatever=date flags
   where:
     date is dd/mm, dd/mm/yy (assumes 20th century!) or dd/mm/yyyy
     flags is ONE or ZERO of 
       o  bd  for a birthday (default)
       o  bir for a birthday (exactly equivalent to `bd')
       o  ann for an anniversary
       o  ev  for an event
     and zero or more of
       o  w<n> to set the warn-in-advance time to n days (don't include the
	 brackets! :)
       o  to<date>
       o  for<days>
               to specify the length of time taken by an event, for example a
	       holiday.

     Comment lines are preceeded by #.
     
     Note: If you deviate from this format, I cannot guarantee anything about
     it's behaviour. In most cases, it will just quietly ignore the error,
     which probably isn't ideal behaviour. Oh, well.

     2003/05/20: Automatic reallocation of output buffer in listsrings() by
                 Sebastian Schmidt <yath@yath.eu.org>.

*/

/* ========== */

#include "birthday.h"

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>

#ifdef UNIX
#include <sys/types.h>
#include <unistd.h>
#include <pwd.h>
#endif

/* ========== */

int skptok(int j, char *ptr);
int evcmp(const void *e1, const void *e2);
char *deffname(void);

struct event *dir_include(char *dir, char *parm, const struct date *today);

/* ========== Global variables */

int iDWarn   = DEF_WARN;
int iMaxWarn = MAX_WARN;
int iMinWarn = MIN_WARN;

const unsigned MLENDAT[]={31,-1,31,30,31,30,31,31,30,31,30,31};

const struct _ftable FTABLE[] =
{
  {"bir",F_TBIRTHDAY},
  {"bd", F_TBIRTHDAY},
  {"ann",F_TANNIVERSARY},
  {"ev", F_TEVENT},
  {"mes", F_TMESSAGE},
  {"w",  F_WTIME_P},
  {"to", F_TODATE},
  {"for", F_FORDAYS},
  {NULL, 0}
};

#ifdef NUMS_AS_WORDS
const char *NUMBERS[10] = {"zero","one","two","three","four","five","six","seven","eight","nine"};
#endif

/* list of directives. These are entered in the file prefixed by '&'. The function should be declared as
   	struct event *dir_func(char *directive, char *parameters);
   and should return a pointer to a NULL-terminated list of extra records, or NULL if there are none.
   This structure will allow us to dynamically add directives, if we wish to do so in the future.
   */

struct {
  const char *text;
  int len;
  struct event *(*func)(char*,char*,const struct date*);
} directlist[] = {
  { "include", 0, dir_include },
  { NULL, 0, NULL }
};

/* ========== */

/* compare the first strlen(a) characters of a and b */
#define strbegcmp(a,b) strncmp(a,b,strlen(a))

/* like strcat(), but lets the buffer automagically grow :-)
 * (needs local variable "size" with the buffer size) */
#define append(where, what) do {				    \
    if (strlen(what) > (size - strlen(where) - 1)) {		    \
      where = xrealloc(where, size + 128 + strlen(what));	    \
      size += 128 + strlen(what);				    \
    }								    \
    strcat(where, what);					    \
  } while(0)

/* ========== */

/* returns delta(d) in days, weeks, months, etc
 * the returned buffer is malloc()ed, do not forget to free() it */
char *tdelta(struct date *d, const struct date *today) {
  int dy, wk, mn, yr;
  char *tmp;
  char *buf = xmalloc(128);
  int size = 128;
  *buf = 0;
  
  switch (delta(d, today)) {
  case 0:
    append(buf, "today");
    return buf;
  case 1:
    append(buf, "tomorrow");
    return buf;
  default:
    /* like delta(), we ignore the year */
    yr=-before(*d,*today);
    mn=d->month - today->month;
    dy=d->day - today->day;
    
    if (dy < 0) {
      dy += mlen(today->month, today->year);
      mn--;
    }
    if (mn < 0) {
      mn += 12;
      yr++;
    }

    wk = (dy/7);
    dy%=7;
    
    append(buf, "in ");
    tmp = ttime(yr, mn, wk, dy);
    append(buf, tmp);
    free(tmp);
    
    if (*(buf + strlen(buf) - 1) == 's')
      append(buf, "'");
    else
      append(buf, "'s");

    append(buf, " time");

    return buf;
  }
}

#ifdef NUMS_AS_WORDS
#define donum(n,txt) do {                          \
      if (n > 0) {                                 \
         if (n < 10) {                             \
            append(buf, NUMBERS[n]);               \
            append(buf, " " txt);                  \
               if (n != 1) {                       \
                  append(buf, "s");                \
               }                                   \
         } else {                                  \
            snprintf(tmp, sizeof(tmp), "%d", n);	\
            append(buf, tmp);                      \
            append(buf, " " txt "s");              \
         }                                         \
         terms--;                                  \
         if (orgterms > 1) {                       \
	         if (terms == 1)                        \
               append(buf, " and ");               \
            else if (terms > 1)                    \
               append(buf, ", ");                  \
         }                                         \
      }                                            \
   } while(0)
#else /* NUMS_AS_WORDS */
#define donum(n,txt) do {                       \
      if (n > 0) {                              \
         snprintf(tmp, sizeof(tmp), "%d", n);   \
         append(buf, tmp);                      \
         append(buf, " " txt);                  \
         if (n != 1)                            \
            append(buf, "s");                   \
         terms--;                               \
         if (orgterms > 1) {                    \
            if (terms == 1)                     \
               append(buf, " and ");            \
            else if (terms > 1)                 \
               append(buf, ", ");               \
         }                                      \
      }                                         \
   } while(0)
#endif /* NUMS_AS_WORDS */

/* returns allocated buffer, don't forget to free() */
char *ttime(int yr, int mn, int wk, int dy) {
  char *buf = xmalloc(128);
  int size = 128;
  int terms, orgterms;
  char tmp[128];
  
  *buf = 0; /* Initialize buffer */
  terms = orgterms = (yr!=0) + (mn!=0) + (wk!=0) + (dy!=0);

  donum(yr, "year");
  donum(mn, "month");
  donum(wk, "week");
  donum(dy, "day");

  return buf;
}
#undef donum

/* lists the birthdays in their string format, one by one, and passes the string
   to a function. */
void liststrings(struct event *evl, prnfunc outf, const struct date *today) {
   int i,j;
   char *buf, *tmp;
   int size;
   
   for (i = 0; evl[i].text != NULL; i++) {
      buf = xmalloc(128);
      *buf = '\0';
      size = 128;
      
      if (evl[i].warn == -1 && delta(&(evl[i].date), today)==0) {
         append(buf, evl[i].text);
      } else if (evl[i].enddate.day == 0) {
	if (delta(&(evl[i].date), today) <= warnperiod(evl[i])) {
            append(buf, evl[i].text);
            append(buf, " ");
            tmp = tdelta(&(evl[i].date), today);
            append(buf, tmp);
            free(tmp);
         }
      } else {
	if (delta(&(evl[i].date), today) <= warnperiod(evl[i])) {
            append(buf, evl[i].text);
            append(buf, " for ");
	         /* +1 because, if the difference between two dates is one day,
	            then the length of an event on those days is two days */
	    j = ddiff(&(evl[i].date),&(evl[i].enddate), today) + 1;
	         tmp = ttime(0, 0, j/7, j%7);
            append(buf, tmp);
            free(tmp);
            append(buf, " ");
            tmp = tdelta(&(evl[i].date), today);
            append(buf, tmp);
	} else if (delta(&(evl[i].enddate), today) <= warnperiod(evl[i])) {
            append(buf, evl[i].text);
            append(buf, " ");
	    j = delta(&(evl[i].enddate), today);
	         if (j) {
               append(buf, "for ");
	            tmp = ttime(0, 0, j/7, j%7);
               append(buf, tmp);
               free(tmp);
               append(buf, " longer");
	         } else {
               append(buf, "finishes today");
	         }
         }
      }
      if (*buf) {
         append(buf, ".");
         outf(buf);
      }
      free(buf);
   }
}

char *
deffname(void)
{
#if defined(UNIX)
  char buf[256];

  strcpy(buf,getpwuid(getuid())->pw_dir);
  strcat(buf, "/" DEFAULT_FILE);

  return strdup(buf);
#elif defined(DOS)
  return strdup(DOSDEFDIR DEFAULT_FILE);
#endif
}
  
/* sort the events by the time before the next time they come up, putting those
   where the start has passed but we are still in the time-period first */
int
evcmp(const void *p1, const void *p2)
{
  struct event *e1=(struct event *)p1;
  struct event *e2=(struct event *)p2;
  unsigned d1,d2;

  /* if the delta for the enddate is less than that for the start date, then we
     have passed the start date but not yet the end date, and so we should
     display the enddate; otherwise, we should display the start date */
  
  d1 = e1->fromtoday;
  d2 = e2->fromtoday;

  if (d1 < d2) return -1;
  if (d1 > d2) return  1;
  
  return strcmp(e1->text, e2->text);
}

/* difference in days between two dates */
/* it is assumed that D1 < D2, and so the result is always positive */

unsigned ddiff(struct date *D1, struct date *D2, const struct date *today)
{
  struct date d1,d2;
  int dd,m;

  /* make working copies */
  d1=*D1;
  d2=*D2;
  
  /* sort out zero years */
  if (d1.year == 0 || d2.year==0) {
    if (d1.year != d2.year) {
      if (d1.year == 0) {
	if (before(d1,d2))
	  d1.year=d2.year;
	else
	  d1.year=d2.year-1;
      } else {
	if (before(d1,d2))
	  d2.year=d1.year;
	else
	  d2.year=d1.year+1;
      }
    } else { /* both years zero */
      /* NB we do actually have to use today's year, to get leap years
	 right. */
      if (before(d1,d2))
	d1.year=d2.year=today->year;
      else {
	d1.year=today->year;
	d2.year=d1.year+1;
      }
    }
  }

  /* now we can actually do the comparison ... */
  dd=0;
  
  /* to start with, we work in months */
  for (m=d1.month; m < d2.month + (d2.year-d1.year)*12; m++)
    dd += mlen(((m-1)%12)+1, d1.year + m/12);

  /* and then we renormalise for the days within the months */
  /* the first month was included in our calculations */
  dd -= d1.day;
  /* but the last one wasn't */
  dd += d2.day;

  return dd;
}

/* actually until the next anniversary of ... */
unsigned delta(struct date *date, const struct date *today)
{
  struct date d;
  unsigned dt, mn;
  
  memcpy(&d, date, sizeof(struct date));
  
  if (before(d, *today)) /* past the end of the year */
    {
      d.year = 1;
    } else {
      d.year = 0;
    }
    
  for (mn = today->month, dt=0; mn < d.month + 12*d.year; mn++)
    dt += mlen(((mn-1)%12) + 1,today->year + mn/12);
  
  dt -= today->day;
  dt += d.day;
  
  return dt;  
}

void scan_date( const char *str, struct date *date) {
  int n;
  n = sscanf(str, "%d/%d/%d", &(date->day), &(date->month), &(date->year));
  if ( n < 3 ) {
    /* didn't read the year */
    date->year=0;
  }
  else {
    /* if our year is only two digits, add 1900 to it ... */
    if(date->year < 100) date->year+=1900;
  }
}

struct event *readlist(char *fname, const struct date *today)
{
  FILE *file;
  int i,j,k,l,d;
  struct event *evl;
  char buf[1024], buf2[1024];
  char *ptr;
  unsigned flags;
  struct event *nevl;
  /* initialise */
  if (fname==NULL) {
    fname=deffname();
  }
  
  if (fname[0] == '-' && fname[1] == 0) {
    /* read from stdin */
    file=stdin;
  } else {
    /* now read it */
    if((file=fopen(fname, "rt"))==NULL) {
      fatal("Unable to open file \"%s\"\n", fname);
    }
  }


  for (i = 0, evl=NULL; fgets(buf, sizeof(buf), file) != NULL; i++) {
    evl = (struct event *) xrealloc(evl, sizeof(struct event) * (i + 1));

    if (*buf == '#' || *buf == '\n')
      {
	i--;
	continue;
      }
    if (*buf == '&') {
      buf[strlen(buf)-1] = 0;
      if ((ptr=strchr(buf+1,' ')) == NULL && (ptr=strchr((buf+1),'\t')) == NULL) {
	ptr=(buf+1)+strlen((buf+1));
      }

      *ptr++=0;
      nevl=NULL;
      k=0;
      for (j=0; directlist[j].text != NULL; j++) {
	if (directlist[j].len == 0) directlist[j].len = strlen(directlist[j].text);
	/*
	  fprintf(stderr, "Checking against directive #%d, %s, which has length %d, against \"%s\" with length %d\n",
		j, directlist[j].text, directlist[j].len, buf+1, ptr-(buf+1)-1);
		*/
	if (directlist[j].len == ptr-(buf+1)-1 && !strncmp(directlist[j].text,(buf+1),directlist[j].len))
	  {
	    nevl = directlist[j].func((buf+1),ptr,today);
	    k=1;
	    break;
	  }
      }
      
      if (nevl != NULL) {
	for (j=0; nevl[j].text != NULL; j++);
	i+=j-1;
	evl = (struct event *) xrealloc(evl, sizeof(struct event) * (i + 1));
	/* in fact, this loop reverses the order of the elements, but we're going to sort them later anyway. */
	for (j=0; nevl[j].text != NULL; j++)
	  evl[i-j]=nevl[j];
      }
      if (!k) {
	fprintf(stderr, "Warning: unrecognised directive \"%s\" ignored.\n", (buf+1));
	i--;
      }
      continue;
    }

    /* parse string in buf */ 
    ptr = strrchr(buf, '='); /* allow '=' in text */
    if(ptr==NULL) /* not a valid line, so ignore it! Cool, huh? */
      {
	fprintf(stderr, "WARNING: Invalid line in input file:\n%s", buf);
	i--;
	continue;
      }
      
    *(ptr++) = 0;  

    scan_date( ptr, &(evl[i].date) );

    /* parse flags */

    evl[i].warn=iDWarn;
    evl[i].enddate.day=evl[i].enddate.month=evl[i].enddate.year=0;

    flags=j=0;
    while(j = skptok(j, ptr),ptr[j]!=0)
      {
	for (k = 0; FTABLE[k].txt != NULL && strncmp(FTABLE[k].txt, ptr + j, strlen(FTABLE[k].txt)); k++);
	switch (FTABLE[k].flag) {
	case F_WTIME_P: /* w<n> -- sets warning time */
	  sscanf(ptr + j, "w %u", &(evl[i].warn));
	  break;
	case F_FORDAYS: /* for<days> -- sets the duration of the event */
	  sscanf(ptr + j, "for %d", &d);
	  evl[i].enddate=evl[i].date;
	  for (l=1; l < d; l++) {
	    evl[i].enddate.day++;
	    if (evl[i].enddate.day > mlen(evl[i].enddate.month,
					  evl[i].enddate.year)) {
	      evl[i].enddate.month++;
	      evl[i].enddate.day=1;
	    }
	    if (evl[i].enddate.month > 12) {
	      evl[i].enddate.year++;
	      evl[i].enddate.month=1;
	    }
	  }
	  break;
	case F_TODATE:
	  l = sscanf(ptr + j, "to %u/%u/%u", &(evl[i].enddate.day), &(evl[i].enddate.month), &(evl[i].enddate.year));
	  if (evl[i].enddate.year < 100) evl[i].enddate.year+=1900;
	  if (l == 2) evl[i].enddate.year=0;
	  break;
	case 0:
	  break;
	default:
	  flags|=FTABLE[k].flag;
	  break;
	}
      }

    /* construct event text */

    switch(flags & F_MTYPE) {
    case F_TBIRTHDAY:
    default: /* assume it's a birthday */
      if (evl[i].date.year != 0) {
	int tmp_age=ydelta(evl[i].date, *today);
	if (tmp_age!=1) {
	  sprintf(buf2, "%s is %d years old", buf, tmp_age);
	} else {
	  sprintf(buf2, "%s is %d year old", buf, tmp_age);
	}
      } else {
	sprintf(buf2, "%s has a birthday", buf);
      }
      break;
    case F_TANNIVERSARY:
      if (evl[i].date.year != 0) {
	sprintf(buf2, "%s %d years ago", buf, ydelta(evl[i].date, *today));
      } else {
	strcpy(buf2, buf);
      }
      break;
    case F_TEVENT:
      /* if a year was specified, and this warning isn't for it, ignore! */
      if ((evl[i].date.year != 0 && ydelta(evl[i].date, *today) != 0) &&
	  (evl[i].enddate.year == 0 || ydelta(evl[i].enddate, *today) != 0)) {
	i--;
	continue;
      }
      strcpy(buf2, buf);
      break;
    case F_TMESSAGE:
      /* Like an event, except that it only comes up on the given date, and no text at all is appended */
      if ((evl[i].date.year != 0 && ydelta(evl[i].date, *today) != 0) &&
	  (evl[i].enddate.year == 0 || ydelta(evl[i].enddate, *today) != 0)) {
	i--;
	continue;
      }
      strcpy(buf2, buf);
      evl[i].warn=-1; /* special code! */
      break;
    }      
    evl[i].text = strdup(buf2);

    /* precalculate the "priority", the time until we next need to
       display something about this event. */
    {
      unsigned d;
      d=delta(&(evl[i].date), today);
      if (evl[i].enddate.day && delta(&(evl[i].enddate), today) < d)
	d=delta(&(evl[i].enddate), today);
      evl[i].fromtoday = d;
    }
  }

  evl = (struct event *) xrealloc(evl, sizeof(struct event) * (i + 1));
  evl[i].date.day=evl[i].date.month=evl[i].date.year=0;
  evl[i].text = (char *) NULL;

  fclose(file);
  free(fname);

  /* NB uses i from above */
  qsort(evl, i, sizeof(struct event), evcmp);
  return evl;
}

int
skptok(int j, char *ptr)
{
  for (; ptr[j] != 0 &&  ptr[j] != ' ' && ptr[j] != '\t' ; j++);
  for (; ptr[j] != 0 && (ptr[j] == ' ' || ptr[j] == '\t'); j++);
  
  return j;
}

/* ---------------------------------------------------------------------- */
/* Functions to parse input file directives */
struct event *dir_include(char *dir, char *parm, const struct date *today)
{
  struct event *evl;

  evl=readlist(strdup(parm), today);

  return evl;
}
