
# hook
cleanup () { true; }

die()
{
	local ret=1
	trap EXIT
	cleanup
	case "$1" in
		[0-9]) ret="$1"; shift ;;
	esac
	[ -z "$@" ] || echo "$@" >&2
	exit $ret
}

checkconnactive()
{
	[ -z "$1" ] && return 0
	ipsec auto --status | awk -v var="$1" '
BEGIN {
	expr="^000 \"" var "\": "
	status=1
}
$0 ~ expr {
	gsub("^000 \"","")
	gsub("\": .*","")
	status=0
	exit
}
END {
	exit status
}
'
	return $?
}

# set $interface, $gateway
defaultrouteinterface()
{
	gateway=
	interface=
	while read -a a; do
		[ "${a[0]}" != "default" ] && continue
		set -- "${a[@]}"
		break
	done < <(ip route show)

	while [ $# -gt 0 ]; do
		token="$1"
		shift
		case "$token" in
			via)
				gateway="$1"
				shift
			;;
			dev)
				interface="$1"
				shift
			;;
		esac
	done
}

# set $ip, $mask, $brd for $1
getfirstipv4addr()
{
	iface="$1"
	ip=
	mask=
	brd=
	[ -z "$iface" ] && return 1

	read -a a < <(ip -o -4 a show dev $iface)
	set -- "${a[@]}"

	while [ $# -gt 0 ]; do
		token="$1"
		shift
		case "$token" in
			inet)
				ip=${1%%/*}
				mask=${1##*/}
				shift
			;;

			brd)
				brd=${1}
				shift
			;;
		esac
	done

	return 0
}
