#!/bin/sh

# As PPPoE is an "on demand" interface we need to re-configure it when it
# becomes up
if [ "$6" != "{{ ifname }}" ]; then
    exit
fi

{% if connect_on_demand is not defined %}
# add some info to syslog
DIALER_PID=$(cat /var/run/{{ ifname }}.pid)
logger -t pppd[$DIALER_PID] "executing $0"

{%   if default_route != 'none' %}
# See https://phabricator.vyos.net/T2248 & T2220. Determine if we are enslaved
# to a VRF, this is needed to properly insert the default route.

SED_OPT="^ip route"
VRF_NAME=""
if [ -d /sys/class/net/{{ ifname }}/upper_* ]; then
    # Determine upper (VRF) interface
    VRF=$(basename $(ls -d /sys/class/net/{{ ifname }}/upper_*))
    # Remove upper_ prefix from result string
    VRF=${VRF#"upper_"}
    # generate new SED command
    SED_OPT="vrf ${VRF}"
    # generate vtysh option
    VRF_NAME="vrf ${VRF}"
fi

{%     if default_route == 'auto' %}
# Only insert a new default route if there is no default route configured
routes=$(vtysh -c "show running-config" | sed -n "/${SED_OPT}/,/!/p" | grep 0.0.0.0/0 | wc -l)
if [ "$routes" -ne 0 ]; then
    exit 1
fi

{%     elif default_route == 'force' %}
# Retrieve current static default routes and remove it from the routing table
vtysh -c "show running-config" | sed -n "/${SED_OPT}/,/!/p" | grep 0.0.0.0/0 | while read route ; do
    vtysh -c "conf t" ${VTY_OPT} -c "no ${route} ${VRF_NAME}"
done
{%     endif %}

# Add default route to default or VRF routing table
vtysh -c "conf t" ${VTY_OPT} -c "ip route 0.0.0.0/0 {{ ifname }} ${VRF_NAME}"
logger -t pppd[$DIALER_PID] "added default route via {{ ifname }} ${VRF_NAME}"
{%   endif %}
{% endif %}