scripts

misc scripts and tools
git clone git://git.2f30.org/scripts
Log | Files | Refs

dyndns-update (1736B)


      1 #!/bin/sh
      2 
      3 BASE=/home/dyndns
      4 
      5 LOCK_FILE=$BASE/dyndns.lock
      6 HOSTS_FILE=$BASE/hosts
      7 ZONE_FILE=$BASE/dyn.2f30.org
      8 ZONE_TEMPLATE_FILE=$ZONE_FILE.template
      9 SERIAL_FILE=$BASE/serial
     10 SERIAL=$(cat $SERIAL_FILE)
     11 
     12 HOST=$1
     13 ADDR=$(echo $SSH_CLIENT | awk '{print $1}')
     14 
     15 if test -z $HOST; then
     16 	echo "missing hostname" 1>&2
     17 	exit 1
     18 fi
     19 
     20 if test -z $ADDR; then
     21 	echo "missing address" 1>&2
     22 	exit 1
     23 fi
     24 
     25 # only IPv4 addresses are supported
     26 expr "$ADDR" : '[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' >/dev/null
     27 if ! test $? -eq 0; then
     28 	echo "invalid address" 1>&2
     29 	exit 1
     30 fi
     31 
     32 umask 077
     33 
     34 (
     35 	flock -w 30 8
     36 
     37 	test -e $HOSTS_FILE || touch $HOSTS_FILE
     38 	test -e $SERIAL_FILE || echo 0 > $SERIAL_FILE
     39 
     40 	# check if host needs updating or not
     41 	while read line; do
     42 		H=$(echo $line | awk '{print $1}')
     43 		A=$(echo $line | awk '{print $2}')
     44 		if test "$H" = "$HOST" -a "$A" = "$ADDR"; then
     45 			echo "$H.dyn.2f30.org is up to date"
     46 			exit 0
     47 		fi
     48 	done < $HOSTS_FILE
     49 
     50 	# update host entry in hosts file
     51 	FOUND=0
     52 	while read line; do
     53 		H=$(echo $line | awk '{print $1}')
     54 		A=$(echo $line | awk '{print $2}')
     55 		if test "$H" = "$HOST"; then
     56 			echo $HOST $ADDR >> $HOSTS_FILE.tmp
     57 			FOUND=1
     58 		else
     59 			echo $H $A >> $HOSTS_FILE.tmp
     60 		fi
     61 	done < $HOSTS_FILE
     62 
     63 	# if host was not found in the hosts file, append it to the end of the file
     64 	if test $FOUND -eq 0; then
     65 		echo $HOST $ADDR >> $HOSTS_FILE.tmp
     66 	fi
     67 
     68 	mv $HOSTS_FILE.tmp $HOSTS_FILE
     69 
     70 	SERIAL=$((SERIAL+1))
     71 	echo $SERIAL > $SERIAL_FILE
     72 	sed "s/%SERIAL%/$SERIAL/g" $ZONE_TEMPLATE_FILE > $ZONE_FILE
     73 
     74 	while read line; do
     75 		H=$(echo $line | awk '{print $1}')
     76 		A=$(echo $line | awk '{print $2}')
     77 		echo "$H\tIN\tA\t$A" >> $ZONE_FILE
     78 	done < $HOSTS_FILE
     79 
     80 	echo "$HOST.dyn.2f30.org updated to $ADDR"
     81 ) 8>$LOCK_FILE