curlgrep-notify/curlgrep.sh

60 lines
1.2 KiB
Bash
Executable file

#!/bin/bash
source "$(dirname $(readlink -f "$0"))/config.sh"
function do_notify {
msg="$1"
curl "http://[::1]:51641/plain" -F message="$msg"
}
function do_one {
if [ "$#" -lt 4 ] ; then
>&2 echo "Missing argument to do_one."
return
fi
url="$1"
pattern="$2"
msg="$3"
elt_id="$4"
state_path="$STATE_DIR/$elt_id"
echo -n "Polling $url"
curl -s "$url" | grep -q "$pattern"
no_match="$?"
if [ "$no_match" -eq 1 ]; then
if [ -f "$state_path" ] ; then
echo "no match anymore"
rm -f "$state_path"
else
echo "still no match"
fi
else # match
if ! [ -f "$state_path" ] ; then # no previous match
echo "now matches"
touch "$state_path"
do_notify "$msg"
else
echo "still matches"
fi
fi
}
if [ "${#URLS[@]}" -ne "${#PATTERNS[@]}" ] \
|| [ "${#URLS[@]}" -ne "${#MESSAGES[@]}" ]
then
>&2 echo "Bad configuration: unbalanced number of elements"
exit 2
fi
mkdir -p "$STATE_DIR"
for elt_id in "${!URLS[@]}"; do
do_one \
"${URLS[$elt_id]}" \
"${PATTERNS[$elt_id]}" \
"${MESSAGES[$elt_id]}" \
"$elt_id"
done