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

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
		echo -e "$(echo 'ar7cfg.ethinterfaces[eth0].ipaddr' | ar7cfgctl -s)\tfritz.box" >> /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
		;;
	*)
		echo "Usage: $0 [load]" 1>&2
		exit 1
		;;
esac

exit 0