-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathwttr
More file actions
executable file
·137 lines (107 loc) · 2.7 KB
/
Copy pathwttr
File metadata and controls
executable file
·137 lines (107 loc) · 2.7 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/usr/bin/sh
# @author nate zhou
# @since 2023,2024,2025,2026
# @depends: libnotify, dunst(or equivalent daemon)
# wttr - weather report script
# This script has completions: `.config/{z,ba}sh/completions/_scripts.{z,ba}sh`
CITY="${HOME}/.cache/city"
WTTR="${HOME}/.cache/wttr"
DAMBLOCKS="${XDG_RUNTIME_DIR}/damblocks.pid"
update_frequency=3600 # in seconds
usage() {
cat << _EOF_
USAGE
$(basename $0) [CITY] [OPTION]
without CITY, read the local cache in $WTTR
OPTIONS
-u,--update update the local cache in $WTTR
-c,--cron to be run as a cron job that checks the last update
time with the defined update_frequency($update_frequency seconds)
-e,--edit edit the CITY in $CITY
-g,--geo) print the city in $CITY
-h,--help print this usage manual
_EOF_
exit 0
}
send_signal() {
kill -44 "$(cat $DAMBLOCKS)"
}
update_cmd() {
curl wttr.in/${city}?format=1
}
notify() {
msg="$1"
[ "$XDG_SESSION_TYPE" != "tty" ] && notify-send -r 23 "$(basename $0)" "$msg"
}
abort() {
msg="$1"
RED='\033[0;31m'
RESET='\033[0m'
echo "${RED}${1}${RESET}"
notify "$msg" >&2
exit 1
}
check_cache() {
wttr=$(cat $WTTR 2>/dev/null)
if [ ! -f "$CITY" ]; then
msg="$CITY doesn't exist, try \"$(basename $0) -e\" first."
abort "$msg"
elif [ -z "$wttr" ]; then
update
fi
}
update() {
city="$(cat $CITY)"
local silent="${1:-false}"
msg=$(update_cmd)
if echo "$msg" | grep -q '°C'; then
echo "$msg" | sed 's/[[:space:]]\+/ /g; s/°C/℃/' | tee "$WTTR"
[ "$silent" != "true" ] && notify "$msg"
exit 0
else
msg="downloading failed, please check the connection to wttr.in"
abort "$msg"
fi
}
get_local_wttr() {
check_cache
wttr=$(cat $WTTR)
msg="$wttr"
echo "$msg"
notify "$msg"
}
get_city_wttr() {
city="$1"
msg=$(update_cmd)
echo "$msg"
notify "$msg"
}
edit_city() {
$EDITOR $CITY
}
print_city() {
cat $CITY
}
cron() {
check_cache
local current_time="$(date +%s)"
local update_time="$(stat -c '%Y' "$WTTR")"
if [ $(( $current_time - $update_time )) -gt "$update_frequency" ]; then
update "true" # silent=true
else
msg="Already update within past $(( $update_frequency / 3600)) hours"
echo $msg
fi
}
trap send_signal EXIT
[ -z "$1" ] && get_local_wttr
if [ -n "$1" ]; then
case "$1" in
-u|--update) update ;;
-c|--cron) cron "$1" ;;
-e|--edit) edit_city ;;
-g|--geo) print_city ;;
-*) usage ;;
*) get_city_wttr "$1" ;;
esac
fi