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

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

case "$1" in
	"")
		mvi /tmp/flash/exhosts
		$0 load
		;;
	load)
		hostname fritz.box

		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
			cat /tmp/flash/exhosts | grep -v "^#" | while read -r ip mac interface host desc; do
				if [ -z "$host" -o "$host" = "*" ]; then
					let hnr="$hnr+1"
					host="pc${hnr}.fritz.box"
				fi

				[ -n "$ip" -a "$ip" != "*" ] && echo -e "$ip\t$host" >> /var/tmp/hosts
				[ -n "$mac" -a "$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=192.168.178.254
		fi
		echo -e "$ipaddr\tfritz.box" >> /var/tmp/hosts
		;;
	*)
		echo "Usage: $0 [load]" 1>&2
		exit 1
		;;
esac

exit 0