#!/bin/bash

# update-known-hosts pe 7.10.2011 17.14.01 +0300
#
# Changes since pe 7.10.2011 16.54.20 +0300:
#	- variable-defined username & server
#	- exit with error if no config
#	- drop ip announcing, do it elsewhere
#
# pe 7.10.2011 16.54.20 +0300: First release



USER=jani
SERVER=mummila
KNOWN_HOSTS=/usr/local/etc/known_hosts
HOSTS=/etc/hosts

function update-hosts () {
	IPFILE=$1
	HOSTNAME=$2
	IP=`sudo -u $USER ssh -qq $SERVER 'cat '$IPFILE`
	test "x$IP" = "x" && return 1
	grep -q $HOSTNAME $HOSTS
	if [ $? -gt 0 ]
	then
		echo -e "$IP\t$HOSTNAME\n" >> $HOSTS
	else
		TEMP=`mktemp`
		awk 'BEGIN {} {if($2=="'$HOSTNAME'") sub(/^.*$/,"'$IP'",$1); print}' $HOSTS > $TEMP
		cp $HOSTS $HOSTS.O && cp $TEMP $HOSTS && rm $TEMP
	fi
}

test -r "${KNOWN_HOSTS}" >/dev/null 2>&1 || exit 1

# reads in lines of "path/to/hostfile=hostname"
for hostline in `cat "${KNOWN_HOSTS}"`
do
	hostpath=`echo "$hostline" | cut -d= -f 1`
	hostname=`echo "$hostline" | cut -d= -f 2`
	test "x$hostpath" = "x" && continue
	test "x$hostname" = "x" && continue
	update-hosts $hostpath $hostname
done
