#!/bin/sh
# CAcert Dev Image - CAcert Developers and Testers Image
# Copyright (C) 2011  CAcert Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


set -e

export LANG=C

# Updates the /etc/hosts and /home/cacert/etc/hosts
# To be called on if-post-up

if [ ! "$1" ]; then
	echo "Usage: $0 HOSTNAME"
	exit 1
fi
hostname="$1"

if ! /sbin/ifconfig "$IFACE" > /dev/null; then
	logger -s -p 'user.err' -t "$0" "ifconfig on interface $IFACE failed"
	exit 0
fi

ip=$(/sbin/ifconfig "$IFACE" | sed -n -e '/^.*inet addr:[[:blank:]]*\([.[:digit:]]\+\).*/{s//\1/;p;q;}')

if ! echo "$ip" | grep -E -q '^[.[:digit:]]+$'; then
	logger -s -p 'user.err' -t $0 "couldn't parse a valid IP address"
	exit 0
fi

repl_pattern=$(printf '/^127\\..*/!{/^.*\\b%s\\b.*/{s/^[.[:digit:]]\\+/%s/;};}' $hostname $ip)

sed --in-place -e $repl_pattern /etc/hosts /home/cacert/etc/hosts

exit 0

