#!/bin/sh

WWANIF=$1

if [ -z "$WWANIF" ]; then
	exit 1
fi

check_iface() {
	local state=$(ubus call network.interface.$WWANIF status 2>/dev/null | jsonfilter -e '@.up' 2>/dev/null)
	if [ "$state" = "true" ]; then
		return 0
	else
		return 1
	fi
}

wait_for_iface() {
	local max_wait=$1
	local i=0
	while [ $i -lt $max_wait ]; do
		if check_iface; then
			return 0
		fi
		sleep 1
		i=$((i + 1))
	done
	return 1
}

if wait_for_iface 10; then
	exit 0
fi

ifup $WWANIF

if wait_for_iface 10; then
	exit 0
fi

ifup $WWANIF
exit 0
