
/*
 *  TIME.C
 *
 *  By Christopher A. Wichura
 *
 *  Note: cannot use strtok() due to parent level's use of it.
 */

#include "includes.h"           /* System include files, system dependent */
#include "uucp.h"               /* Uucp definitions and parameters */
#include <log.h>
#include "version.h"

typedef struct tm   Time;

char Days[7][3] = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

int
CheckTimeRestrictions(timeStr)
char *timeStr;
{
    Time *tm;
    char *ptr;
    int work1;
    int work2;
    int starth, startm;
    int endh,	endm;
    char Hours[24];
    int result;
    int day;

    if (strnicmp("Any", timeStr, 3) == 0)
	return (SUCCESS);

    if (strnicmp("Never", timeStr, 5) == 0)
	return (FAIL);

    {
	time_t t;
	time (&t);
	tm = localtime(&t);
    }

    result = FAIL;

    for (ptr = timeStr; ptr; ptr = strpbrk(ptr, ",")) {
	if (*ptr == ',')
	    ++ptr;

	day = 0;

	while (isalpha(*ptr)) {
	    for (work1 = 0; work1 < 7; ++work1) {
		if (strnicmp(ptr, Days[work1], 2) == 0) {
		    day |= 1L << work1;
		    ptr += 2;
		    break;
		}
	    }
	    if (work1 == 7) {
		ulog(-1, "Illegal DOW Field (L.Sys): %s", timeStr);
		return(FAIL);
	    }
	}

	if (day == 0)
	    day = -1;

	if (sscanf(ptr, "%d:%d-%d:%d", &starth, &startm, &endh, &endm) != 4) {
	    ulog(-1, "Illegal Time Range Field (L.Sys): %s", timeStr);
	    return(FAIL);
	}

	/*
	 * at this point we have start and end times.  check them against
	 * current system time
	 */

	setmem(Hours, sizeof(Hours), 0);

	work1 = endh - starth;
	if (work1 < 0)
	    work1 += 24;

	work1 = starth + work1;
	work2 = starth;

	while (work2 <= work1) {
	    Hours[work2++] = 1;

	    if (work2 == 24)
		work1 -= 24, work2 -=24;
	}

	for (;;) {
	    if (!(day & 1L << tm->tm_wday))
		break;
	    if (!Hours[tm->tm_hour])
		break;
	    if (tm->tm_hour == starth && tm->tm_min < startm)
		break;
	    if (tm->tm_hour == endh && tm->tm_min > endm)
		break;
	    return(SUCCESS);
	}
    }
    return (FAIL);
}

