#! /bin/sh

# Author: Cumulus Networks <dev-support@cumulusnetworks.com>

export PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/cumulus/bin

# This script does setup for clagd, including argument setup,
# and then execs clagd or exits with a failure.
# It can only be run from systemd, e.g.: systemctl start clagd

NAME=clagd
DAEMON=/usr/sbin/$NAME

# set up for failure if default file is missing
CLAGD_PEER_IP=""
CLAGD_PEER_IF=""
CLAGD_SYS_MAC=""
CLAGD_PRIORITY=""
CLAGD_BACKUP_IP=""
CLAGD_BACKUP_VRF=""
CLAGD_VXLAN_ANYCAST_IP=""
CLAGD_ARGS=""

failrun=0

# The default file is created by ifupdown if clagd is configured
# If the file is not present, don't continue
if [ ! -r /etc/default/$NAME ]; then
    echo "Not configured.  Edit /etc/network/interfaces to enable"
    failrun=5
else
    . /etc/default/$NAME

    [ -z "$CLAGD_PEER_IP" ] && \
	  echo "No peer IP address provided. Not starting clagd service" \
	  && failrun=2
    [ -z "$CLAGD_PEER_IF" ] && \
	  echo "No peer interface provided. Not starting clagd service" \
	  && failrun=2
    [ -z "$CLAGD_SYS_MAC" ] && \
	  echo "No system MAC provided. Not starting clagd service" \
	  && failrun=2
fi

[ -z "$NOTIFY_SOCKET" ] && echo "Must be run from systemd" \
    && failrun=1

if [ $failrun -ne 0 ]
then
    # exit value of 2, or 5 will prevent systemd from restarting us
    # (as set in RestartPreventExitStatus in the service file).
    # exit status of 5 is "successful" for case where clagd is not
    # enabled via /etc/network/interfaces (and the generated default file)
    exit ${failrun}
fi

[ -n "$CLAGD_BACKUP_VRF" ] && \
    CLAGD_ARGS="--backupVrf ${CLAGD_BACKUP_VRF} ${CLAGD_ARGS}"
[ -n "$CLAGD_BACKUP_IP" ] && \
    CLAGD_ARGS="--backupIp ${CLAGD_BACKUP_IP} ${CLAGD_ARGS}"
[ -n "$CLAGD_VXLAN_ANYCAST_IP" ] && \
    CLAGD_ARGS="--vxlanAnycast ${CLAGD_VXLAN_ANYCAST_IP} ${CLAGD_ARGS}"
[ -n "$CLAGD_PRIORITY" ] && \
    CLAGD_ARGS="--priority ${CLAGD_PRIORITY} ${CLAGD_ARGS}"

# Do cleanup first, in case this is a restart where clagd may not have
# cleaned up prior to exitting.
. /lib/clagctl-utils/clagCleanup

exec $DAEMON --daemon $CLAGD_PEER_IP $CLAGD_PEER_IF $CLAGD_SYS_MAC $CLAGD_ARGS
