#! /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

# Trap signals used by switchd to notify its status to clagd 
# until clagd signal handlers are initialized to avoid clagd 
# process from exiting due to the signal. 
trap '' 34 35 36 37
NAME=clagd
DAEMON=/usr/sbin/$NAME

# set up for failure if default file is missing
CLAGD_ENABLE=no
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 "Clagd config parameter missing, not starting clagd. Confirm /etc/network/interfaces configuration."
    failrun=5
else
    . /etc/default/$NAME
    if [ -n "$REQUIRED_ARGS" ]; then 
        echo "Clagd config parameter missing, not starting clagd -${REQUIRED_ARGS}" 
        failrun=5
    else  
        [ ! "$CLAGD_ENABLE" = "yes" ] && \
            echo "Not enabled.  Edit /etc/network/interfaces to enable" \
            && failrun=5

        [ -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
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)
    exec python -c "import cumulus.sdnotify;\
    import sys;\
    cumulus.sdnotify.sd_notify(0, 'READY=1');sys.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
