#!/usr/bin/bash
# Copyright EnterpriseDB Corporation, 2013-2023. All Rights Reserved.

usage() {
    echo $"Usage: $0 add4      <interface name> <IPv4 address/prefix>"
    echo $"       $0 add6      <interface name> <IPv6 address/prefix>"
    echo $"       $0 del       <interface name> <IP address/prefix>"
    echo $"       $0 runarping <interface name> <IPv4 address>"
    exit 1
}

#
# run arping after acquiring an IPv4 VIP
#
runArping() {
    candidates="/usr/sbin/arping /usr/bin/arping"
    for candidate in ${candidates}
    do
        [[ -x "$ARPING_CMD" ]] && break
        ARPING_CMD="$candidate"
    done

    # handle either iputils-arping or arping
    ${ARPING_CMD} -V 2>&1 | grep "iputils"  >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        ${ARPING_CMD} -q -c 3 -U -I "${1}" "${2}"
        return $?
    else
        ${ARPING_CMD} -q -c 3 -P -U -i "${1}" "${2}"
        return $?
    fi
}

#
# add the VIP address to the interface and run arping
#
add4() {
    /sbin/ip addr add "${2}" dev "${1}"
    if [ $? -ne 0 ]; then
        return 1
    else
        # split addr/prefix on the '/'
        x="${2}"
        xArry=("${x//\// }")
        runArping "${1}" "${xArry[0]}"
        return $?
    fi
}

#
# add the IPv6 VIP address to the interface
#
add6() {
    /sbin/ip addr add "${2}" dev "${1}"
    return $?
}

#
# release the VIP address from the interface
#
del() {
    /sbin/ip addr del "${2}" dev "${1}"
    return $?
}

# make sure we at least have the add/del command
if [ $# -lt 1 ]; then
    usage
fi

command=$1
shift

case "$command" in
  add4)
        if [ $# -eq 2 ]; then
            add4 "$@"
            exit $?
        else
            usage
        fi
        ;;
  runarping)
        if [ $# -eq 2 ]; then
            runArping "$@"
            exit $?
        else
            usage
        fi
        ;;
  add6)
        if [ $# -eq 2 ]; then
            add6 "$@"
            exit $?
        else
            usage
        fi
        ;;
  del)
        if [ $# -eq 2 ]; then
            del "$@"
            exit $?
        else
            usage
        fi
        ;;
  *)
        usage
esac
