#!/bin/vbash
# Enable or disable the DHCP WAN (bond0.53). The ONLY part of the failover that
# touches VyOS configuration.
#
# PPPoE deliberately does NOT appear here any more, and should not be added back
# for symmetry. `set interfaces pppoe pppoe0 disable` unlinks
# /etc/ppp/peers/pppoe0 -- interfaces_pppoe.py treats `disable` and `delete`
# identically -- and that path is pppd's options file, so the resting state
# destroyed what the promotion path needed and the unit restart-looped (47 times,
# zero sessions at the AC). It also made a pppoe node able to fail this commit
# and take the 10 gig down with it: `interfaces pppoe` is priority 322 and one
# invalid node fails the whole commit. PPPoE is now gated at the systemd unit
# instead; see migration/ppp-vrrp-gate.conf and vrrp-wan-reconcile.
#
# bond0.53 stays here because its lease is bound to a cloned MAC and only VyOS
# config can move a MAC between boxes.
#
# `source /opt/vyatta/etc/functions/script-template` must be the FIRST thing the
# script does. Sourced after an if, an exec and a mkdir it terminated the script
# inside the source, rc=0, no output -- the caller reported success having done
# nothing. Only a single assignment may precede it (the template resets the
# positional parameters), which is the shape /config/vyos-known-good uses.
#
#   vrrp-wan-apply enable    take the DHCP WAN
#   vrrp-wan-apply disable   release it
MODE="${1:-}"
source /opt/vyatta/etc/functions/script-template

CONF=/config/vrrp-wan.conf
[ -r "$CONF" ] && . "$CONF"
WAN_VIF="${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"; }

configure
if [ "$MODE" = enable ]; then
    # Guarded: `delete` of an absent node aborts the whole batch with
    # "Nothing to delete", which once left the box detected-but-unfixed.
    wan_disabled && delete interfaces bonding bond0 vif ${WAN_VIF} disable
else
    wan_disabled || set interfaces bonding bond0 vif ${WAN_VIF} disable
fi
# Report the commit's verdict. This script previously ended on `exit` (a
# script-template function) and returned 0 even after "Commit failed", so the
# reconciler logged a release that had not happened -- the worst kind of failure
# for something whose 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
