-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathget-daytime-period
executable file
·90 lines (78 loc) · 2.25 KB
/
get-daytime-period
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
#!/bin/sh
#
# Get/print the daytime period ("Night", "Day), possibly from redshift
# ("Night" / "Daytime" / "Transition").
#
# This uses DEFAULT_LATLON by default, because the geoclue provider is too
# fragile. The result is cached for 10 minutes.
is_remote() {
[ -n "$SSH_CONNECTION" ] && return
# Container in OpenVZ?
[ -r /proc/user_beancounters ] && ! [ -d /proc/bc ]
}
is_remote && USE_REDSHIFT=0 || USE_REDSHIFT=1
# Do not use geoclue by default, too slow and fragile.
# TODO: provide a method to easily update the latlonfile.
USE_GEOCLUE=0
GEOCLUE_TIMEOUT=2s
CACHE_SECONDS=600
if [ "$USE_REDSHIFT" = 1 ] && ! hash redshift 2> /dev/null; then
echo "redshift not found." >&2
USE_REDSHIFT=0
fi
cachefile=/tmp/redshift-period
ok_to_cache=1
get_period_by_hour() {
hour=$(date +%H)
if [ "$hour" -gt 8 ] && [ "$hour" -lt 20 ]; then
printf "Daytime"
else
printf "Night"
fi
}
# If not using `redshift`, just look at the current hour.
if [ "$USE_REDSHIFT" = 0 ]; then
get_period_by_hour
exit
fi
if [ -e "$cachefile" ]; then
if [ "$(stat --format=%Y $cachefile)" -gt $(( $(date +%s) - CACHE_SECONDS )) ]; then
cat $cachefile
exit
fi
fi
# Try geoclue.
if [ "$USE_GEOCLUE" = 1 ]; then
geoclue_period=$(timeout $GEOCLUE_TIMEOUT redshift -l geoclue2 -p 2>/dev/null)
timeout_ret=$?
if [ "$timeout_ret" = 0 ]; then
period=$(echo "$geoclue_period" | grep "^Period")
else
if [ "$timeout_ret" = 124 ]; then
echo 'WARNING: redshift with geoclue timed out.' >&2
else
echo "WARNING: redshift failed with exit code $timeout_ret." >&2
fi
ok_to_cache=0
fi
fi
if [ -z "$period" ]; then
# Default lat/lon when geoclue is not used.
DEFAULT_LATLON="$(dotfiles-decrypt U2FsdGVkX19+ff4P8pvhS2TzsJkKwrDGk/vD1IoXgdEbj3r9+4hfXsGpNfVqxkrR)"
if [ -z "$DEFAULT_LATLON" ]; then
echo "ERROR: $(basename "$0"): DEFAULT_LATLON is not defined." >&2
exit 1
fi
period=$(redshift -l "$DEFAULT_LATLON" -p 2>/dev/null | grep "^Period")
fi
if [ -z "$period" ]; then
echo "WARNING: failed to determine period using redshift." >&2
echo "Falling back to get_period_by_hour." >&2
get_period_by_hour
exit
fi
period="${period#Period: }"
if [ "$ok_to_cache" = 1 ]; then
printf '%s' "$period" > $cachefile
fi
printf '%s' "$period"