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

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/exhosts
		$0 load
		;;
	load)
		hostname $(ar7hostname)

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

		echo -e "127.0.0.1\tlocalhost" > /var/tmp/hosts
		touch /var/tmp/ethers

		# ATA fix
		mode="$(echo 'ar7cfg.mode' | ar7cfgctl -s)"
		if [ "$mode" = "dsldmode_bridge" -o \
		     "$mode" = "dsldmode_full_bridge" ]; then
			if [ "$(echo 'ar7cfg.wan_bridge_with_dhcpc' | ar7cfgctl -s)" = "no" -a \
			     "$(echo 'ar7cfg.dhcpc_use_static_dns' | ar7cfgctl -s)" = "yes" ]; then
				(
					echo "nameserver $(echo 'servercfg.dns1' | ar7cfgctl -s)"
					echo "nameserver $(echo 'servercfg.dns2' | ar7cfgctl -s)"
				) > /var/tmp/resolv.conf
			fi
		fi

		if [ -r /tmp/flash/exhosts ]; then
			egrep -v '^(#|[[:space:]]*$)' /tmp/flash/exhosts |
				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

		ethmode=$(echo 'ar7cfg.ethmode' | ar7cfgctl -s)
		devname=lan
		case "$ethmode" in
			ethmode_bridge)
				section=brinterfaces
				break
				;;
			ethmode_router)
				section=ethinterfaces
				break
				;;
			*)
				section=ethinterfaces
		esac
		ipaddr=$(ar7ipaddr $section $devname)
		if [ -z "$ipaddr" ] ; then
		  devname=eth0
		  ipaddr=$(ar7ipaddr $section $devname)
		fi
		if [ -z "$ipaddr" ] ; then
		  ipaddr=169.254.1.1
		fi
		echo -e "$ipaddr\tfritz.box\t$(ar7hostname)" >> /var/tmp/hosts
		;;
	*)
		echo "Usage: $0 [load]" 1>&2
		exit 1
		;;
esac

exit 0
