#!/bin/sh

. /etc/functions.sh

local PARA=
local OPNAME="$1"
local SAID=$(echo $2 | awk -F "tun." '{print "tun0x"$2}')
local PEERIP="$3"
local MYSUBNET="$4"
local PEERSUBNET="$5"
local TNAME="$6"

# echo "OPNAME $OPNAME SAID $SAID PEERIP $PEERIP MYSUBNET $MYSUBNET PEERSUBNET $PEERSUBNET" > /dev/console

replaceStaticRoute() {
	local esrc="$1"
	local edst="$2"
	local esaid="$3"

	ipsec eroute --del --eraf inet --src $esrc --dst $edst
	ipsec eroute --add --eraf inet --src $esrc --dst $edst --said $esaid
}

set_more_route() {
	local mTUNNEL
	local mNET
	local mMASK
	local mSAID
	
	config_get mTUNNEL  $1	tunnel	
	if [ "$mTUNNEL" == "$TNAME" ]; then
		config_get mNET  $1	net
		config_get mMASK $1	mask
		mSAID=$(ipsec spi | grep "$PEERIP" | grep -m 1 "IPIP: dir=out" | awk '{print $1}')
		
		ipsec eroute --add --eraf inet --src $MYSUBNET --dst $mNET/$mMASK --said $mSAID
		route add -net $mNET netmask $mMASK dev ipsec0		
	fi
}

del_more_route() {
	local mTUNNEL
	local mNET
	local mMASK
	
	config_get mTUNNEL  $1	tunnel	
	if [ "$mTUNNEL" == "$TNAME" ]; then
		config_get mNET  $1	net
		config_get mMASK $1	mask
		
		ipsec eroute --del --eraf inet --src $MYSUBNET --dst $mNET/$mMASK
		route del -net $mNET netmask $mMASK dev ipsec0		
	fi
}

case "$OPNAME" in
replace) 
	ipsec eroute | grep "$PEERIP" | grep -v "$SAID" | awk '{print $2" "$4}'  | while read line
	do
		PARA="$line"
#		echo "PARA $PARA" > /dev/console
		replaceStaticRoute $PARA $SAID
	done
;;
add)
	config_load /etc/config/m_route
	config_foreach set_more_route more-route
;;
del)
	config_load /etc/config/m_route
	config_foreach del_more_route more-route
;;
*)
#	echo "IPSEC set static route none" > /dev/console
;;
esac

# ipsec eroute > /dev/console