#!/bin/sh
# auto-generated by zebra service (frr.py)
FRR_CONF="${frr_conf}"
FRR_SBIN_SEARCH="${frr_sbin_search}"
FRR_BIN_SEARCH="${frr_bin_search}"
FRR_STATE_DIR="${frr_state_dir}"

searchforprog()
{
    prog=$1
    searchpath=$@
    ret=
    for p in $searchpath; do
        if [ -x $p/$prog ]; then
            ret=$p
            break
        fi
    done
    echo $ret
}

confcheck()
{
    CONF_DIR=`dirname $FRR_CONF`
    # if /etc/frr exists, point /etc/frr/frr.conf -> CONF_DIR
    if [ "$CONF_DIR" != "/etc/frr" ] && [ -d /etc/frr ] && [ ! -e /etc/frr/frr.conf ]; then
        ln -s $CONF_DIR/frr.conf /etc/frr/frr.conf
    fi
    # if /etc/frr exists, point /etc/frr/vtysh.conf -> CONF_DIR
    if [ "$CONF_DIR" != "/etc/frr" ] && [ -d /etc/frr ] && [ ! -e /etc/frr/vtysh.conf ]; then
        ln -s $CONF_DIR/vtysh.conf /etc/frr/vtysh.conf
    fi
}

bootdaemon()
{
    FRR_SBIN_DIR=$(searchforprog $1 $FRR_SBIN_SEARCH)
    if [ "z$FRR_SBIN_DIR" = "z" ]; then
        echo "ERROR: FRR's '$1' daemon not found in search path:"
        echo "  $FRR_SBIN_SEARCH"
        return 1
    fi

    flags=""

    if [ "$1" = "pimd" ] && \\
        grep -E -q '^[[:space:]]*router[[:space:]]+pim6[[:space:]]*$' $FRR_CONF; then
        flags="$flags -6"
    fi

    #force FRR to use CORE generated conf file
    flags="$flags -d -f $FRR_CONF"
    $FRR_SBIN_DIR/$1 $flags

    if [ "$?" != "0" ]; then
        echo "ERROR: FRR's '$1' daemon failed to start!:"
        return 1
    fi
}

bootfrr()
{
    FRR_BIN_DIR=$(searchforprog 'vtysh' $FRR_BIN_SEARCH)
    if [ "z$FRR_BIN_DIR" = "z" ]; then
        echo "ERROR: FRR's 'vtysh' program not found in search path:"
        echo "  $FRR_BIN_SEARCH"
        return 1
    fi

    # fix /var/run/frr permissions
    id -u frr 2>/dev/null >/dev/null
    if [ "$?" = "0" ]; then
        chown frr $FRR_STATE_DIR
    fi

    bootdaemon "zebra"
    if grep -q "^ip route " $FRR_CONF; then
        bootdaemon "staticd"
    fi
    for r in rip ripng ospf6 ospf bgp babel; do
        if grep -q "^router \\<$${}{r}\\>" $FRR_CONF; then
            bootdaemon "$${}{r}d"
        fi
    done

    if grep -E -q '^[[:space:]]*router[[:space:]]+pim6?[[:space:]]*$' $FRR_CONF; then
        bootdaemon "pimd"
    fi

    $FRR_BIN_DIR/vtysh -b
}

if [ "$1" != "zebra" ]; then
    echo "WARNING: '$1': all FRR daemons are launched by the 'zebra' service!"
    exit 1
fi
confcheck
bootfrr

# reset interfaces
% for ifc, _, _ , _ in interfaces:
ip link set dev ${ifc.name} down
sleep 1
ip link set dev ${ifc.name} up
% endfor
