aboutsummaryrefslogtreecommitdiffstats
path: root/src/entry.c
blob: 13208ca3c3c559da618449660600a4a7f5db54cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "entry.h"

#include <assert.h>

static time_t rt;

/* super inefficient, but should best-possible avoid any weird leap
 * years/seconds/dst-problems/other future changes */
time_t* entry_is_active(struct entry_s *e, time_t now)
{
	struct tm t, ttmp, *tmp;
	time_t rttmp, now_plus_warn, now_minus_stay;
	
	assert(e != NULL);

	tmp = localtime(&now);
	if (tmp == NULL)
		return NULL;
	t = *tmp;
	ttmp = t;

	t.tm_year += e->warn.year;
	t.tm_mon += e->warn.month;
	t.tm_mday += e->warn.day;
	t.tm_hour += e->warn.hour;
	t.tm_min += e->warn.minute;
	t.tm_sec += e->warn.second;

	now_plus_warn = mktime(&t);

	ttmp.tm_year -= e->stay.year;
	ttmp.tm_mon -= e->stay.month;
	ttmp.tm_mday -= e->stay.day;
	ttmp.tm_hour -= e->stay.hour;
	ttmp.tm_min -= e->stay.minute;
	ttmp.tm_sec -= e->stay.second;

	now_minus_stay = mktime(&ttmp);

	if (now_plus_warn == -1 || now_minus_stay == -1)
		return NULL;

	if (e->type == ENTRY_TYPE_ON) {
		if (e->start >= now_minus_stay && e->start <= now_plus_warn) {
			rt = e->start;
			return &rt;
		}

		return NULL;
	}

	if (e->has_end && now_minus_stay > e->end)
		return NULL;

	tmp = localtime( &(e->start) );
	if (tmp == NULL)
		return NULL;
	t = *tmp;

	for (rt = e->start;;) {
		if (rt > now_plus_warn)
			return NULL;

		if (rt >= now_minus_stay)
			return &rt;

		ttmp = t;

		t.tm_year += e->every.year;
		t.tm_mon  += e->every.month;
		t.tm_mday += e->every.day;
		t.tm_hour += e->every.hour;
		t.tm_min  += e->every.minute;
		t.tm_sec  += e->every.second;

		rt = mktime(&t);

		if (rt == -1) {
			rttmp = mktime(&ttmp);
			if (rttmp == -1)
				return NULL;

			tmp = localtime(&rttmp);
			if (tmp == NULL)
				return NULL;
			t = *tmp;

			t.tm_year += e->every.year;
			t.tm_mon  += e->every.month;
			t.tm_mday += e->every.day;
			t.tm_hour += e->every.hour;
			t.tm_min  += e->every.minute;
			t.tm_sec  += e->every.second;

			rt = mktime(&t);

			if (rt == -1)
				return NULL;
		}
	}
}