#!/bin/bash

# (c) 2014-2015 Sam Nazarko
# email@samnazarko.co.uk

if grep -q nfsroot /proc/cmdline
then
	if ! grep -q MANUAL /proc/net/pnp
	then
		cp /proc/net/pnp /etc/resolv.conf
		cp /proc/sys/kernel/hostname /etc/hostname
		hostname=$(cat /etc/hostname)
		hostline="127.0.1.1		${hostname}"
		if ! grep -q $hostline /etc/hosts
		then
			echo $hostline >> /etc/hosts
		fi
	else
		domain=$(dmesg | egrep -o 'domain=[0-9a-zA-Z][0-9a-zA-Z.-]*[0-9a-zA-Z]' | awk -F= '{print $NF}')
		nameservers=$(dmesg | sed 's/\,/\n/g' | egrep -o 'nameserver[0-9]+=[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' | awk -F= '{print $NF}')

		echo "domain ${domain}" >/etc/resolv.conf
		for ns in ${nameservers[@]}
		do
			if ! grep -w "$ns" /etc/resolv.conf
			then
				echo "nameserver ${ns}" >> /etc/resolv.conf
			fi
		done
	fi
	exec /usr/sbin/connmand -n --nodnsproxy --noresolvmodify --config=/etc/connman.conf
else
	if echo "$dnsproxy" | grep -iqw no; then
		exec /usr/sbin/connmand -n --nodnsproxy --config=/etc/connman.conf
	else
		exec /usr/sbin/connmand -n --config=/etc/connman.conf
	fi
fi
