#!/bin/vbash
# Enable or disable the WAN. Split out from vrrp-wan-reconcile for one reason:
# `source /opt/vyatta/etc/functions/script-template` must be the FIRST thing the
# script does. Sourced after a few statements -- an if, an exec, a mkdir -- it
# silently terminated the script; `set -x` showed execution stopping inside the
# source with no error and rc=0, so the reconciler reported success having done
# nothing. Only a single assignment may precede it (the template resets the
# positional parameters, so the mode is captured first), which is the same shape
# /config/vyos-known-good uses.
#
#   vrrp-wan-apply enable    take the WAN
#   vrrp-wan-apply disable   release it
MODE="${1:-}"
source /opt/vyatta/etc/functions/script-template

WAN_VIF=53
cfg() { /opt/vyatta/bin/vyatta-op-cmd-wrapper show configuration commands 2>/dev/null; }
wan_disabled(){ cfg | grep -q "vif ${WAN_VIF} disable"; }
ppp_disabled(){ cfg | grep -q "pppoe pppoe0 disable"; }
# Only touch pppoe0 if it is actually configured. `set interfaces pppoe pppoe0
# disable` on a box that has no pppoe0 CREATES the node with nothing but
# `disable`, and VyOS then refuses the commit with "Physical source-interface
# required for pppoe0!" -- taking the bond0.53 change down with it, because one
# invalid node fails the whole commit. Seen on the labsim secondary, which has
# no PPPoE; production has it on both, so this would have been an untested path
# that only ever ran during a failover.
ppp_exists(){ cfg | grep -q "pppoe pppoe0 source-interface"; }

configure
if [ "$MODE" = enable ]; then
    # Guarded: `delete` of an absent node aborts the whole batch with
    # "Nothing to delete", which left the box detected-but-unfixed.
    wan_disabled && delete interfaces bonding bond0 vif ${WAN_VIF} disable
    ppp_exists && ppp_disabled && delete interfaces pppoe pppoe0 disable
else
    wan_disabled || set interfaces bonding bond0 vif ${WAN_VIF} disable
    ppp_exists && { ppp_disabled || set interfaces pppoe pppoe0 disable; }
fi
# Report the commit's verdict. The script previously ended on `exit` (a
# script-template function) and returned 0 even after "Commit failed", so the
# reconciler logged a successful release that had not happened -- the worst kind
# of failure for something whose whole job is to keep two routers from holding
# one WAN.
if commit 2>&1 | tee /tmp/vrrp-wan-commit.log | grep -qi "commit failed"; then
    logger -t vrrp-wan "COMMIT FAILED applying '$MODE' -- see /tmp/vrrp-wan-commit.log"
    exit 1
fi
exit
