#!/bin/sh /etc/rc.common

START=98
USE_PROCD=1

enable_lan_ping() {
	uci -q set firewall.floatip_lan_offline.enabled=0 || return 0
	uci changes | grep -Fq 'firewall.floatip_lan_offline.enabled' || return 0
	uci commit firewall
	/etc/init.d/firewall reload
}

start_service() {
	config_load floatip
	config_get_bool enabled "main" enabled 0
	/usr/libexec/floatip.sh down
	[[ "$enabled" = 1 ]] || {
		enable_lan_ping
		return 0
	}
	[[ "`uci -q get network.lan.proto`" = "static" ]] || {
		logger -s -t floatip "LAN proto is not static"
		return 0
	}
	local lan_iface="`uci -q get network.lan.device`"
	if [ -z "$lan_iface" ]; then
		logger -s -t floatip "Cannot get LAN device"
		return 0
	fi
	local set_ip set_prefix
	config_get set_ip "main" set_ip
	[[ -n "$set_ip" ]] || return 0
	if [[ "$set_ip" = "*/*" ]]; then
		eval "$(ipcalc.sh "$set_ip" )";set_prefix=$PREFIX;set_ip=$IP
	else
		set_prefix=32
	fi
	local lan_ip="`uci -q get network.lan.ipaddr`"
	[[ -n "$lan_ip" ]] || return 0
	local lan_net lan_prefix set_net ip
	local in_range=0
	local lan_netmask="`uci -q get network.lan.netmask`"
	for ip in $lan_ip; do
		if [[ "$ip" = "*/*" ]]; then
			eval "$(ipcalc.sh $ip )";lan_net=$NETWORK;lan_prefix=$PREFIX
		else
			# prefix=32 if not present
			[[ -n "$lan_netmask" ]] || continue
			eval "$(ipcalc.sh $ip $lan_netmask )";lan_net=$NETWORK;lan_prefix=$PREFIX
		fi
		[[ "$set_prefix" -ge "$lan_prefix" ]] || continue
		eval "$(ipcalc.sh $set_ip/$lan_prefix )";set_net=$NETWORK
		[[ "$set_net" = "$lan_net" ]] && {
			[[ "$set_prefix" = 32 ]] && set_prefix=$lan_prefix
			in_range=1
			break
		}
	done

	[[ $in_range = 1 ]] || {
		logger -s -t floatip "float ip is not belong to any LAN subnets"
		return 0
	}
	procd_open_instance
	procd_set_param command /usr/libexec/floatip.sh up "$lan_iface" "$set_prefix"
	procd_set_param stderr 1
	procd_set_param file /etc/config/floatip
	procd_close_instance
}

service_stopped() {
	/usr/libexec/floatip.sh down
	enable_lan_ping
}

service_triggers() {
	procd_add_reload_trigger "network" "floatip"
}
