#! /bin/bash

# This script performs initialization for switchd that needs to be done prior to
# starting switchd.

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/usr/cumulus/bin
DESC="Cumulus Networks switch chip daemon"
NAME=switchd
DAEMON=/usr/sbin/$NAME
PIDFILE=/run/$NAME.pid
SCRIPTNAME=$0
BCMDIR=/etc/bcm.d
SWITCHD_INIT=/etc/cumulus/switchd.init


#
# Generate switchd configuration

do_setup_random_number()
{
    if [ ! -d "/var/lib/switchd/" ]
    then
        mkdir -p /var/lib/switchd/
    fi

    if [ ! -s "/var/lib/switchd/ecmp_rand_seed" ]
    then
        openssl rand 4 | hexdump -e '/4 "%u\n"' > /var/lib/switchd/ecmp_rand_seed
    fi

    if [ ! -s "/var/lib/switchd/ecmp_rand_seed1" ]
    then
        openssl rand 4 | hexdump -e '/4 "%u\n"' > /var/lib/switchd/ecmp_rand_seed1
    fi
}

do_init()
{
	# run any switchd setup scripts
	#
	if [ -x $SWITCHD_INIT ]; then
		$SWITCHD_INIT || { echo $SWITCHD_INIT failed; return 2; }
	fi

        # generate datapath configurations
        #
        if [ -x /usr/lib/cumulus/datapath-config ]; then
                /usr/lib/cumulus/datapath-config ||
                { echo datapath-config failed: $?; return 2; }
        fi

        # generate the backend config file
        #
        if [ -x /usr/lib/cumulus/generate-backend-config ]; then
                /usr/lib/cumulus/generate-backend-config ||
                { echo generate-backend-config failed: $?; return 2; }
        fi

        # setup random for use as load-balance seed
        do_setup_random_number
}  

#
# Function that starts the daemon/service
#
do_start()
{
	# Signal clagd (if clagd is running, so ignore errors) on switchd
	# state changes (starting) with SIGRTMIN+2
	# Python thinks SIGRTMIN is 34, so in the clagd code this is SIGRTMIN
	/usr/bin/killall -q -s 34 clagd

	/usr/sbin/switchd -lic
	RETVAL="$?"
	if [ "$RETVAL" = 1 ]; then
		logger -s -p syslog.alert -- "No license.  Switchd will not start"
		return 2;
	fi

	if [ "$RETVAL" = 2 ]; then
	    logger -s -p syslog.alert -- "No valid license.  Switchd will not start"
	    return 2;
	fi

	rm -f /run/problems/switchd* # licensed; clear previous fatal errors

	if [ -n "$SEPARATE_ROUTING" ]; then
		separate_routing $SEPARATE_ROUTING
		SEPARATE_ROUTING_ARGS="-s -t 1"
	fi

	do_init 
	RETVAL="$?"
	if [ "$RETVAL" = 2 ]; then
        # 42 is handled in unit script so we do not attempt a restart if there are
        # initialization script failures
        logger -s -p syslog.alert -- "Generation of configuration files failed.  Switchd will not start"
        return 42;
	fi
	RETVAL="$?"

	# be sure fuse mount point is present
	mkdir -p /cumulus/switchd 2>/dev/null
  
	return $RETVAL
}

do_reload()
{
        /usr/lib/cumulus/update-ports -f -w
        RETVAL="$?"
        if [ "$RETVAL" != 0 ]; then
             logger -s -p syslog.alert -- "Generation of configuration files failed.  Switchd will not reload"
             return $RETVAL;
        fi

        CMD="cl-consistency-check --datapath-syntax-check -t /etc/cumulus/datapath/traffic.conf -d /etc/mlx/datapath/datapath.conf"
        $CMD
        RETVAL="$?"
        if [ "$RETVAL" != 0 ]; then
            logger -s -p syslog.alert -- "Validation of consistency-checker failed.  Execute '$CMD' to get error details."
            return $RETVAL;
        fi

        return $RETVAL
}

sendsigs_omit() {
        OMITDIR=/run/sendsigs.omit.d
        mkdir -p $OMITDIR
        ln -sf $PIDFILE $OMITDIR/switchd
}

# error out if no arguments.

case "$1" in
  start)
	echo "Initializing $DESC $NAME"
	do_start
	rval=$?
	case "$rval" in
		0) sendsigs_omit ;;
		*) exit $rval ;;
	esac

	# Signal clagd (if clagd is running, so ignore errors) on switchd
	# state changes.  35==SIGRTMIN+3 tells clag switchd is ready.
	# Python thinks SIGRTMIN is 34, so in the clagd code this is SIGRTMIN+1
	# It needs to be set after switchd becomes ready, so loop until
	# switchd is active or failed.
	setsid /bin/sh -c '(while ! systemctl -q is-active switchd; do 
	  systemctl -q is-failed switchd && exit 1; sleep 3; done;
	  /usr/bin/killall -q -s 35 clagd)&'

	exec /usr/sbin/switchd ${SEPARATE_ROUTING_ARGS} $VX
	;;

  reload)
        plat=`/usr/bin/platform-detect -c`
        if [[ ! ${plat} =~ "mlx" ]]; then
            # No support for non mellanox platform
            logger -s -p syslog.alert -- "switchd reload is not supported for current ASIC: ${plat}"
            exit 0;
        fi
        
        do_reload
        RETVAL="$?"
        if [ "$RETVAL" != 0 ]; then
             exit $RETVAL;
        fi

	;;
  *)
	echo "Usage: $SCRIPTNAME start" >&2
	exit 3
	;;
esac

exit 0
