Add nsd-update
[shutils.git] / nsd-dynipwatch
1 #!/bin/bash
2
3 logfile=
4
5 while true; do
6 case $1 in
7 --log) logfile=$2; shift ;;
8 -h|--help)
9 echo "$0 [-f] [--log logfile] zonefile host watchfile"
10 exit 0
11 ;;
12 *) break ;;
13 esac
14 shift
15 done
16
17
18 zonefile=$1
19 host=$2
20 watchfile=$3
21 [ -z "${logfile}" ] && logfile="/var/log/nsd-dynipwatch-${host}.log"
22
23 echo "logfile: ${logfile}"
24
25
26
27 function getAddrFromZonefile # <host> <zonefile>
28 {
29 egrep "^$1\\s.*\\sA\\s.*" $2 | egrep -o "([0-9]+\\.)+[0-9]+"
30 }
31
32 function setAddrInZonefile # <host> <zonefile> <addr>
33 {
34 sed -i -e "s_^\\($1\\s.*A\\s.*\\s\\)\\([0-9]\\+\\.\\)\\+[0-9]\\+_\\1$3_g" "$2"
35 }
36
37 function getSerialFromZonefile # <zonefile>
38 {
39 awk '/; serial/{print$1}' "$1"
40 }
41
42 function setSerialInZonefile # <zonefile> <serial>
43 {
44 sed -i -e "s_^\\(.*\\s\\)[0-9]\+\\(\\s\\+; serial.*\\)_\\1$2\\2_g" "$1"
45 }
46
47 function run()
48 {
49 while true; do
50 inotifywait -q -e close_write "${watchfile}" > /dev/null
51 oldip=`getAddrFromZonefile "${host}" "${zonefile}"`
52 newip=`cat ${watchfile}`
53 echo "`date '+%a %F %T'` :: ${oldip} => ${newip}."
54
55 if ! echo "${newip}" | egrep -q "^([0-9]+\\.)+[0-9]+$" ; then
56 echo "Wrong format of new IP address."
57 continue
58 fi
59
60 if ! [ "${oldip}" = "${newip}" ]; then
61 serial=`getSerialFromZonefile "${zonefile}"`
62 serial=$(( $serial + 1))
63 echo " Update IP address. New serial ${serial}."
64 setAddrInZonefile "${host}" "${zonefile}" "${newip}"
65 setSerialInZonefile "${zonefile}" "${serial}"
66 nsdc rebuild && nsdc reload && nsdc notify
67 fi
68 done
69 }
70
71 run >> $logfile
72