#!/bin/sh
#
# Usage: modhosts [load]

VERBOSE_RC_CONF=n
. /etc/init.d/rc.conf

ar7ipaddr () {
	local SEC=$1
	local DEV=$2
	echo $(echo 'ar7cfg.'$SEC'['$DEV'].ipaddr' | ar7cfgctl -s)
}

ar7hostname () {
	HOSTNAME=$(echo servercfg.hostname | ar7cfgctl -s)
	HOSTNAME=$(eval echo $HOSTNAME)
	if [ "$HOSTNAME" != "(none)" ]; then
		echo $HOSTNAME
	else
		echo $CONFIG_HOSTNAME
	fi
}

isip () {
	echo $1 | egrep '^[[:digit:]]{1,3}(\.[[:digit:]]{1,3}){3}$' >/dev/null
}
ismac () {
	echo $1 | egrep '^[[:xdigit:]]{2}(:[[:xdigit:]]{2}){5}$' >/dev/null
}

case $1 in
	"")
		mvi /tmp/flash/mod/hosts
		$0 load
		;;
	load)
		_hostname=$(ar7hostname)
		hostname $_hostname

		echo "nameserver 127.0.0.1" > /etc/resolv.conf
		_domain=$(echo $_hostname |cut -d "." -f2-)
		[ -n "$_domain" ] && echo "domain $_domain" >> /etc/resolv.conf

		rm -f /var/tmp/hosts
		rm -f /var/tmp/ethers

		touch /var/tmp/hosts
		touch /var/tmp/ethers

		if [ -r /tmp/flash/mod/hosts ]; then
			egrep -v '^(#|[[:space:]]*$)' /tmp/flash/mod/hosts |
				while read -r ip mac interface host desc; do
					if [ -z "$host" -o "$host" = "*" ]; then
						let hnr="$hnr+1"
						host="pc${hnr}"
					fi

					isip $ip && echo -e "${ip}\t${host} $desc" >> /var/tmp/hosts
					ismac $mac && echo -e "${mac}\t${host}" >> /var/tmp/ethers
				done
		fi

		if ! egrep "^127.0.0.1([[:space:]]+[^[:space:]#]+)*[[:space:]]+localhost($|[[:space:]#])" /var/tmp/hosts -q 2>/dev/null; then
			echo -e "127.0.0.1\tlocalhost" >> /var/tmp/hosts
		fi

		ethmode=$(echo 'ar7cfg.ethmode' | ar7cfgctl -s)
		case $ethmode in
			ethmode_bridge)
				devname=lan
				fallback=eth0
				section=brinterfaces
				break
				;;
			ethmode_router)
				devname=eth0
				fallback=lan
				section=ethinterfaces
				break
				;;
			*)
				devname=eth0
				fallback=lan
				section=ethinterfaces
				;;
		esac
		ipaddr=$(ar7ipaddr $section $devname)
		[ -z "$ipaddr" ] && ipaddr=$(ar7ipaddr $section $fallback)
		[ -z "$ipaddr" ] && ipaddr=169.254.1.1
		[ -d /usr/www.nas ] && nas_hostname="fritz.nas\t"
		if ! egrep "^$ipaddr[[:space:]]" /var/tmp/hosts -q 2>/dev/null; then
			echo -e "$ipaddr\tfritz.box\t$nas_hostname$_hostname" >> /var/tmp/hosts
		fi
		;;
	*)
		echo "Usage: $0 [load]" 1>&2
		exit 1
		;;
esac

exit 0