#!/bin/sh

UCARP=/usr/sbin/ucarp
EXTRA_PARAMS=""

if [ ! -x $UCARP ]; then
    exit 0
fi

if [ -z "$IF_UCARP_UPSCRIPT" ]; then
    IF_UCARP_UPSCRIPT=/usr/share/ucarp/vip-up
fi

if [ -z "$IF_UCARP_DOWNSCRIPT" ]; then
    IF_UCARP_DOWNSCRIPT=/usr/share/ucarp/vip-down
fi

if [ -n "$IF_UCARP_MASTER" ]; then
    if ! expr "$IF_UCARP_MASTER" : "no\|off\|false\|0" > /dev/null; then
        EXTRA_PARAMS="-P"
    fi
fi

if [ -n "$IF_UCARP_ADVSKEW" ]; then
    EXTRA_PARAMS="$EXTRA_PARAMS -k $IF_UCARP_ADVSKEW"
fi

if [ -n "$IF_UCARP_ADVBASE" ]; then
    EXTRA_PARAMS="$EXTRA_PARAMS -b $IF_UCARP_ADVBASE"
fi

if [ -n "$IF_UCARP_DEADRATIO" ]; then
    EXTRA_PARAMS="$EXTRA_PARAMS -r $IF_UCARP_DEADRATIO"
fi

if [ -n "$IF_UCARP_NOMCAST" ]; then
    if ! expr "$IF_UCARP_NOMCAST" : "no\|off\|false\|0" > /dev/null; then
        EXTRA_PARAMS="$EXTRA_PARAMS -M"
    fi
fi

if [ -n "$IF_UCARP_NOSPOOF" ]; then
    if ! expr "$IF_UCARP_NOSPOOF" : "no\|off\|false\|0" > /dev/null; then
        EXTRA_PARAMS="$EXTRA_PARAMS -F"
    fi
fi

if [ -n "$IF_UCARP_XPARAM" ]; then
    EXTRA_PARAMS="$EXTRA_PARAMS -x $IF_UCARP_XPARAM"
fi

# Prefer a password file over a plain password: a password given on the
# ucarp command line is visible to every user in the process list.
if [ -n "$IF_UCARP_PASSFILE" ]; then
    PASS_PARAMS="-o $IF_UCARP_PASSFILE"
elif [ -n "$IF_UCARP_PASSWORD" ]; then
    PASS_PARAMS="-p $IF_UCARP_PASSWORD"
else
    PASS_PARAMS=""
fi

if [ -n "$IF_UCARP_VID" ] && [ -n "$IF_UCARP_VIP" ] && \
        [ -n "$PASS_PARAMS" ]; then
    # ifupdown exports IFUPDOWN_<iface>=parent-lock while hook scripts
    # run. The ucarp daemon inherits them, making ifupdown reject the
    # ifup call from vip-up as a recursion. Start ucarp without those
    # variables.
    CLEAN_ENV=$(env | sed -n 's/^\(IFUPDOWN_[^=]*\)=.*/-u \1/p' | tr '\n' ' ')

    env $CLEAN_ENV $UCARP -i $IFACE -s $IF_ADDRESS -B -z -v $IF_UCARP_VID \
        $PASS_PARAMS -a $IF_UCARP_VIP -u $IF_UCARP_UPSCRIPT \
        -d $IF_UCARP_DOWNSCRIPT $EXTRA_PARAMS || \
        logger -t ucarp "failed to start ucarp on $IFACE (exit $?)"
elif [ -n "$IF_UCARP_VID" ] || [ -n "$IF_UCARP_VIP" ] || \
        [ -n "$PASS_PARAMS" ]; then
    logger -t ucarp "incomplete ucarp configuration for $IFACE:" \
        "ucarp-vid, ucarp-vip and ucarp-password/ucarp-passfile" \
        "are all required"
fi

# A ucarp startup failure must not make "ifup" consider the whole
# interface non-operational (see #661591).
exit 0

# vi:ai sw=4 ts=4 tw=0 et
