summaryrefslogtreecommitdiffstats
path: root/w3watch
blob: 71d495118cc01da130a82fd7b16f786f11b66793 (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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/bin/bash

DRYRUN=false
ROOTDIR="${HOME}/.w3watch"
CACHEDIR="${ROOTDIR}/cache"
LOCKFILE="${ROOTDIR}/lock"
CONFIGFILE="${ROOTDIR}/config"
CONFIGSAMPLE='/usr/share/doc/w3watch/config.sample'
LYNX='/usr/bin/lynx --connect_timeout 10 --read_timeout 10 -stderr'

if [ ! -d "${ROOTDIR}" ]; then
	install -D "${CONFIGSAMPLE}" "${CONFIGFILE}"
	mkdir -p "${CACHEDIR}"
fi

if [ ! -r "${CONFIGFILE}" ]; then
	echo "${CONFIGFILE} not found!"
	exit 1
fi

if [ ! -d "${CACHEDIR}" ]; then
	mkdir -p "${CACHEDIR}"
fi

if [ -r "${LOCKFILE}" ]; then
	echo "w3watch is locked by ${LOCKFILE}"
	exit 1
fi

touch "${LOCKFILE}"


quit() {
	rm -f "${LOCKFILE}"
	exit $1
}

usage() {
	echo "usage: ${0} [option]"
	echo 'options:'
	echo '	-e	edit config'
	echo '	-l	list config'
	echo '	-d	dump output and discard any changes'
	echo '	-c	check for updates'
	echo ''
}

edit() {
	${EDITOR} "${CONFIGFILE}"
	return $?
}

list() {
	grep '^[^#]' "${CONFIGFILE}"
}

check() {
	grep '^[^#]' "${CONFIGFILE}" | while read line; do
		data=(${line})
		url="${data[0]}"
		filter="${data[@]:1}"

		if echo "$url}" | grep -q '^@'; then
			url="$(echo "${url}" | cut -c 1 --complement -)"
			dump=$($LYNX -source "$url")
		else
			dump=$($LYNX -dump "$url")
		fi

		if [ $? -ne 0 ]; then
			continue
		fi

		if [ "${filter}" != "" ]; then
			dump=$(echo "${dump}" | eval "${filter}")
		fi

		if $DRYRUN; then
			echo "$dump"
		else
			sum=$(echo "${line}" | sha1sum | awk '{print $1;}')
			cachefile="${CACHEDIR}/${sum}"

			if [ -f "$cachefile" ]; then
				echo "$dump" | diff -u \
					--label "local copy from $(/usr/bin/stat --printf='%y' ${cachefile})" "$cachefile" \
					--label "${url}" - \
				|| echo
			fi

			echo "$dump" > "$cachefile"
		fi
	done
}

collectGarbage() {
	for cacheEntry in "${CACHEDIR}/"*; do
		cacheSum=$(basename "$cacheEntry")

		grep '^[^#]' "${CONFIGFILE}" | while read configEntry; do
			configSum=$(echo "$configEntry" | sha1sum | awk '{print $1;}')

			if [ "$cacheSum" == "$configSum" ]; then
				return 1
			fi
		done && rm -f $cacheEntry
	done
}


while getopts 'eldc' option; do
	case $option in
		e)	edit; quit $?;;
		l)	list; quit 0;;
		d)	DRYRUN=true; check; quit 0;;
		c)	check; collectGarbage; quit 0;;
		*)	usage; quit -1;;
	esac
done

usage
quit -1