#!/bin/sh

source /etc/pmnetconfig/funcs

${LOG} "${CMROUTES}"
NetCfgCalcPrio $CMINTERFACE

# pppd sets the interface address, so we don't have to.
# Also, we assume that non-PPP interfaces always connect
# to the Internet.
CMTCPWND=""
ISPPP=`expr $CMINTERFACE : ppp[0-9]`
ISRMNET=`expr $CMINTERFACE : rmnet[0-9]`
ISCSCOTUNVPN=`expr $CMINTERFACE : cscotun[0-9]`
ISTUN=`expr $CMINTERFACE : tun[0-9]`

if [ "$ISPPP" -ne 4 ] && [ "$ISRMNET" -ne 6 ] && [ "$ISTUN" -ne 4 ] && [ "$ISCSCOTUNVPN" -ne 8 ]; then
    NetCfgSetAddr
    CMSERVICES=$((${CMSERVICES} | ${CMSVCINTERNET}))
fi

# First, we configure the main routing table.
TBL=""
NetCfgSetRoute $CMROUTES

# Set default gateway in the main routing table
# only if this interface connects to the Internet.
# Also, we want to use this interface's DNS servers
# to resolve Internet names only if this interface
# connects to the Internet.
${LOG} "Service ${CMSERVICES}"
if [ $((${CMSERVICES} & ${CMSVCINTERNET})) -ne 0 ]; then
    NetCfgSetDefgw $CMDEFGW
    NetCfgSetDns $CMDNSSERVERS
fi

# Now we configure the interface-specific routing table.
# Note that the link-route is set only in this
# interface-specific table and not in the main table
# since NetCfgSetAddr above sets the interface IP address
# and that causes a link-route to be automatically
# set in the main table.
NetCfgCalcTblNum $CMINTERFACE
TBL="table $CMTBLNUM"
NetCfgSetRoute $CMROUTES
NetCfgSetDefgw $CMDEFGW
NetCfgSetLinkRoute $CMNETADDR $CMPREFIXLEN $CMINTERFACE $CMIPADDR
NetCfgSetSrcRule $CMIPADDR $CMTBLNUM

NetCfgSetDnsRules $CMDNSSERVERS
NetCfgSetDnsServersForDomains

# Configure NAT for BT-PAN wireless modem feature.
# We delete the nat rule first (in case it doesn't exist, 
# the delete will fail but that's ok; we just want to 
# make sure the rule doesn't exist before we go ahead and
# add it). Hmmm, should consider doing a -R here instead
# of a -D followed by a -A.
# We also enable IP forwarding here.
# TODO: Add iptables rule to prevent routing between WiFi and WAN.
if [ ${CMINTERFACE} = ${CMBTINTERFACENAME} ] || [ ${CMINTERFACE} = ${CMBRINTERFACENAME} ]; then
    ${LOG} "${IPTABLES} -t nat -D POSTROUTING -s $CMNETADDR/$CMPREFIXLEN -j MASQUERADE"
    ${IPTABLES} -t nat -D POSTROUTING -s $CMNETADDR/$CMPREFIXLEN -j MASQUERADE
    ${LOG} "${IPTABLES} -t nat -A POSTROUTING -s $CMNETADDR/$CMPREFIXLEN -j MASQUERADE"
    ${IPTABLES} -t nat -A POSTROUTING -s $CMNETADDR/$CMPREFIXLEN -j MASQUERADE
fi
# Evaluate Static Routes directory and evaluate routes that would be forced over this interface
NetCfgEvalStaticRoutes $CMNETWORKTECHTYPE $CMDEFGW

NetCfgCommit
