#!/bin/sh
rm -f /etc/network/interfaces.d/eth0
rm -f /etc/network/interfaces.d/wlan0
rm -f /etc/dnsmasq.hosts
rm -f /etc/dnsmasq.d/eth0.conf
rm -f /etc/dnsmasq.d/wlan0.conf
rm -f /etc/resolv.conf

if [ -f /run/setup ]; then
	(
		if [ -r /run/air ]; then
			address='192.168.1.34'
		else
			address='192.168.1.33'
		fi
		
		echo "auto eth0"
		echo "iface eth0 inet static"
		echo -e "\taddress ${address}"
		echo -e "\tnetmask 255.255.0.0"
	) > /etc/network/interfaces.d/eth0
	exit 0
fi

HOSTNAME=$(uci -q get keenfalcon.lan.hostname)
NETMASK=$(uci -q get keenfalcon.lan.netmask)
GATEWAY=$(uci -q get keenfalcon.lan.gateway)
NAMESERVER=$(uci -q get keenfalcon.lan.nameserver)
DOMAIN=$(uci -q get keenfalcon.lan.domain)
DHCP=$(uci -q get keenfalcon.lan.dhcp)

if [ -n "${HOSTNAME}" ]; then
	echo -e "${HOSTNAME}" > /etc/hostname
	hostname ${HOSTNAME}
else
	HOSTNAME=$(hostname)
fi

if [ -z "${DOMAIN}" ]; then
	DOMAIN=local
fi

(
	echo "bind-interfaces"
	echo "domain=${DOMAIN}"
	if [ -n "${NAMESERVER}" ]; then
        	echo "server=${NAMESERVER}"
	fi
	echo "addn-hosts=/etc/dnsmasq.hosts"
	echo "dhcp-option=3,0.0.0.0"
        echo "dhcp-option=6,0.0.0.0"
	echo "dhcp-option=119,${DOMAIN}"
	echo "dhcp-option=58,60"
	echo "dhcp-option=59,60"
	echo "dhcp-script=/usr/share/udhcpc/default.script.d/keenfalcon-dhcp-hook"
) > /etc/dnsmasq.conf

(
	echo -e "10.1.49.64\t${HOSTNAME}\t${HOSTNAME}.${DOMAIN}"
) > /etc/dnsmasq.hosts

ADDRESS=$(uci -q get keenfalcon.lan.address)

if [ "${ADDRESS}" != "dhcp" ]; then
	if [ -z "${NETMASK}" ]; then
		NETMASK="255.255.255.0"
	fi
	
	if [ -n "${ADDRESS}" ]; then
		(
			echo "auto eth0"
			echo "iface eth0 inet static"
			echo -e "\taddress ${ADDRESS}"
			echo -e "\tnetmask ${NETMASK}"
			if [ -n "${GATEWAY}" ]; then
				echo -e "\tgateway ${GATEWAY}"
			fi	
		) > /etc/network/interfaces.d/eth0
	fi
	
        if [ -n "${DHCP}" ]; then
        	(
        		echo "interface=eth0"
        		echo "dhcp-range=${DHCP},2m"
        	) > /etc/dnsmasq.d/eth0.conf
        fi

	(
		echo "domain ${DOMAIN}"
		echo "search ${DOMAIN}"
		echo "nameserver 127.0.0.1"
	) >> /etc/resolv.conf
else
	(
		echo "auto eth0"
		echo "iface eth0 inet dhcp"
		echo -e "\tclient udhcpc"
		if [ -z "${HOSTNAME}" ]; then
			HOSTNAME=$(hostname)
		fi
		echo -e "\thostname ${HOSTNAME}"
	) > /etc/network/interfaces.d/eth0
fi

if [ -e /sys/class/net/wlan0 ]; then
	(
		echo "interface=wlan0"
		echo "dhcp-range=10.1.49.1,10.1.49.61,255.255.255.192,2m"
	) > /etc/dnsmasq.d/wlan0.conf


	(
		echo "auto wlan0"
		echo "iface wlan0 inet static"
		echo -e "\taddress 10.1.49.62"
		echo -e "\tnetmask 255.255.255.192"
	) > /etc/network/interfaces.d/wlan0
fi
