#!/bin/sh

# Create /etc/resolv.conf from various sources.

#exec > /tmp/resolvconf.out 2>/tmp/resolvconf.err
#set -x

interface="$1"
dynamic="$2"

if [ "X$interface" = Xwlan0 ]
then
	RESOLV_CONF=/tmp/resolv.conf.wlan0
	RESOLV_CONF_TMP=/tmp/resolv.conf.wlan0.tmp
	RESOLV_STATIC=/storage/etc/resolv.conf.wlan0.static
	RESOLV_DHCP4=/tmp/resolv.conf.wlan0.dhcp4
	RESOLV_RA6=/tmp/resolv.conf.wlan0.ra6
else
	RESOLV_CONF=/tmp/resolv.conf
	RESOLV_CONF_TMP=/tmp/resolv.conf.tmp
	RESOLV_STATIC=/storage/etc/resolv.conf.static
	RESOLV_DHCP4=/tmp/resolv.conf.dhcp4
	RESOLV_RA6=/tmp/resolv.conf.ra6
fi

if [ -f /etc/init.d/chronyd ]
then
	CHRONY="/etc/init.d/chronyd restart"       # Kick chrony
else
	CHRONY="/etc/init.d/ntpd restart"       # Kick chrony
fi

# Static address configuration may be broken. When switching back to DHCP
# also ignore statically configured DNS resolvers
if [ X"$dynamic" != Xdynamic ]
then
	if [ -f $RESOLV_STATIC ]
	then
		# Static
		cat $RESOLV_STATIC > $RESOLV_CONF_TMP
		mv $RESOLV_CONF_TMP $RESOLV_CONF
		$CHRONY &
		exit 0
	fi
fi

# Dynamic
if [ -f $RESOLV_DHCP4 -a -f $RESOLV_RA6 ]
then
	paste -d'\n' $RESOLV_DHCP4 $RESOLV_RA6 > $RESOLV_CONF_TMP
elif [ -f $RESOLV_DHCP4 ]
then
	cat $RESOLV_DHCP4 > $RESOLV_CONF_TMP
elif [ -f $RESOLV_RA6 ]
then
	cat $RESOLV_RA6 > $RESOLV_CONF_TMP
fi
mv $RESOLV_CONF_TMP $RESOLV_CONF
$CHRONY &
