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

START=94
USE_PROCD=1

readonly __ok__='\033[0;32m[\xe2\x9c\x93]\033[0m'
readonly __fail__='\033[0;31m[\xe2\x9c\x97]\033[0m'
readonly __pass__='\033[0;33m[-]\033[0m'
readonly __error__='\033[0;31mERROR\033[0m'

output() { local msg=$(echo -n "${1/$p_name /service }" | sed 's|\\033\[[0-9]\?;\?[0-9]\?[0-9]\?m||g'); [ -n "$2" ] && [ ! $(($verbosity & $2)) -gt 0 ] && return 0; [ -t 1 ] && echo -e -n "$1"; [ $(echo -e -n "$msg" | wc -l) -gt 0 ] && logger -t "${PKG_NAME:-service} [$$]" "$(echo -e -n ${logmsg}${msg})" && logmsg='' || logmsg=${logmsg}${msg}; }
PKG_NAME="${PKG_NAME:-vpnbypass}"; p_name="${PKG_NAME} ${PKG_VERSION}"

is_enabled() {
	config_load $PKG_NAME
	config_get verbosity    'config' 'verbosity' '2'
	config_get TID          'config' 'table_number' '200'
	config_get IPSET        'config' 'ipset'  'vpnbypass'
	config_get FW_MARK      'config' 'fw_mark' '0x010000'
	config_get FW_MASK      'config' 'fw_mask' '0xff0000'
	source /lib/functions/network.sh
	return 0
}

ipt() {
    local d=$(echo $* | sed s/-A/-D/g)
    [ "$d" != "$*" ] && iptables $d >/dev/null 2>&1
    d=$(echo $* | sed s/-I/-D/g)
    [ "$d" != "$*" ] && iptables $d >/dev/null 2>&1
		d=$(echo $* | sed s/-N/-F/g)
    [ "$d" != "$*" ] && iptables $d >/dev/null 2>&1
		d=$(echo $* | sed s/-N/-X/g)
    [ "$d" != "$*" ] && iptables $d >/dev/null 2>&1

		iptables $* >/dev/null 2>&1
}

#boot() { ubus -t 30 wait_for network.interface.wan && { rc_procd start_service; rc_procd service_triggers; } || output "ERROR: $p_name failed to settle network interface!\n"; }

start_service() {
	local ll c=1
  config_load vpnbypass
  is_enabled || return 1
  config_get lports   'config' 'localport'
  config_get rports   'config' 'remoteport'
  config_get routes   'config' 'remotesubnet'
  config_get ranges   'config' 'localsubnet'
  config_get domains  'config' 'domain'

	procd_open_instance
	procd_set_param stdout 1
	procd_set_param stderr 1
	procd_close_instance

	while : ; do
		network_find_wan wan_if4; [ -n "wan_if4" ] && network_get_gateway wan_gw $wan_if4;
		[ $c -ge 25 -o -n "$wan_gw" ] && break
		output "$p_name waiting for wan gateway...\n"; sleep 2; network_flush_cache; let "c+=1";
	done
	[ -z "$wan_gw" ] && output "$__error__: $p_name could not discover wan gateway IP!\n" && exit 1

	ipt -t mangle -N VPNBYPASS; ipt -t mangle -A PREROUTING -m mark --mark 0x00/${FW_MASK} -g VPNBYPASS;
	ipt -t mangle -A VPNBYPASS -m set --match-set $IPSET dst -j MARK --set-mark ${FW_MARK}/${FW_MASK}
	ip rule del fwmark "$FW_MARK" table "$TID" >/dev/null 2>&1; ipset -q flush "$IPSET"; ipset -q destroy "$IPSET";
	ip route flush table "$TID"; ip route flush cache;
	ip route add default via "$wan_gw" table "$TID"; ip route flush cache;
	ipset -q -exist create "$IPSET" hash:ip; ipset -q flush "$IPSET"
	ip rule add fwmark "$FW_MARK" table "$TID"
	{ modprobe xt_set; modprobe ip_set; modprobe ip_set_hash_ip; } >/dev/null 2>&1
	for ll in ${ranges}; do ipt -t mangle -I VPNBYPASS 1 -j MARK --set-mark ${FW_MARK}/${FW_MASK} -s "$ll"; done
	for ll in ${lports}; do ipt -t mangle -I VPNBYPASS 1 -j MARK --set-mark ${FW_MARK}/${FW_MASK} -p tcp -m multiport --sport "${ll//-/:}"; done
	for ll in ${routes}; do ipt -t mangle -I VPNBYPASS 1 -j MARK --set-mark ${FW_MARK}/${FW_MASK} -d "$ll"; done
	for ll in ${rports}; do ipt -t mangle -I VPNBYPASS 1 -j MARK --set-mark ${FW_MARK}/${FW_MASK} -p tcp -m multiport --dport "${ll//-/:}"; done
	output "$p_name started with TID: $TID; FW_MARK: $FW_MARK\n"
}

stop_service() {
	local ll
  is_enabled || return 1

	ip rule del fwmark "$FW_MARK" table "$TID" >/dev/null 2>&1; ipset -q flush "$IPSET"; ipset -q destroy "$IPSET";
	ip route flush table "$TID"; ip route flush cache;
	ipt -t mangle -D PREROUTING -m mark --mark 0x00/${FW_MASK} -g VPNBYPASS
	ipt -t mangle -F VPNBYPASS; ipt -t mangle -X VPNBYPASS;
	output "$p_name stopped\n"
}

reload_service(){
	start_service
}

st_load_interfaces(){ local d; config_get d $1 ifname; [ "$1" == "$wan_if4" -o "$d" != "${d/tun}" -o "$d" != "${d/tap}" ] && ifaces=" ${1} ${ifaces}"; }
service_triggers() {
		local ifaces n
		procd_add_reload_trigger 'vpnbypass'
		procd_open_trigger
		procd_add_config_trigger "config.change" "vpnbypass" /etc/init.d/vpnbypass reload
		for n in $ifaces; do procd_add_interface_trigger "interface.*" "$n" /etc/init.d/openvpn-policy-routing reload; done;
		procd_close_trigger
}
