summaryrefslogtreecommitdiffstats
path: root/w3watch
blob: c310253b9d628f304fc9e09f30c00348b14f5109 (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
123
124
125
126
127
#!/bin/bash

DRYRUN=false
ROOTDIR="${HOME}/.w3watch"
CACHEDIR="${ROOTDIR}/cache"
LOCKFILE="${ROOTDIR}/lock"
CONFIGFILE="${ROOTDIR}/config"
CONFIGSAMPLE='/usr/share/doc/w3watch/config.sample'

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 -v '^#' "${CONFIGFILE}"
}

check() {
	while read line; do
		if  echo "${line}" | grep -q -v '^#'; then
			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
				quit 1
			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
		fi
	done < "${CONFIGFILE}"
}

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

		while read configEntry; do
			if  echo "${configEntry}" | grep -q -v '^#'; then
				configSum=$(echo "$configEntry" | sha1sum | awk '{print $1;}')

				if [ "$cacheSum" == "$configSum" ]; then
					continue 2
				fi
			fi
		done < "${CONFIGFILE}"

		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