#!/bin/sh

if [ "$ACTION" = ifup ]; then
	. /etc/functions.sh

	include /lib/network
	scan_interfaces

	update_tunnel() {
		local cfg="$1"

		local proto
		config_get proto "$cfg" proto
		[ "$proto" = 6to4 ] || return 0

		local wandev
		config_get wandev "$cfg" wan_device "$(find_6to4_wanif)"
		[ "$wandev" = "$DEVICE" ] || return 0

		local wanip=$(find_6to4_wanip "$wandev")

		[ -n "$wanip" ] && {
			lsmod | grep -q ^sit || {
				logger -t 6to4 "Tunneling driver not loaded yet, deferring action"
				exit 0
			}

			uci_set_state network "$cfg" ipaddr "$wanip"
			( ifup "$cfg" )&
		}
	}

	config_foreach update_tunnel interface
fi