#!/bin/sh

################################################################################
#
# Copyright (C) 2016 Cumulus Networks Inc. All rights reserved
#
################################################################################

# This script adds an IPv6 and/or IPv4 address to the supplied interface, for
# internal chassis communication.
# 

SetIpv6Address()
{
    local INTF=${1}
    local IF_INFO=${2}
    local IPV6_ADDR

    # Get the IPv6 link local address for this card
    IPV6_ADDR=$(/usr/lib/cumulus/chassis-info -m) || {
        echo "ERROR: Unable determine chassis IPv6 management address. Is this a chassis?"
        return
    }

    # Does this card have an IPv6 Link Local Address?
    if [ "${IPV6_ADDR}" != "None" ] ; then

        # Is the address already assigned?
        echo "${IF_INFO}" | /bin/grep "inet6 ${IPV6_ADDR}/64 scope link" || {
            # Assign the address to the interface
            /bin/ip address add ${IPV6_ADDR}/64 scope link dev ${INTF} || {
                echo "ERROR: Assigning IPv6 address ${IPV6_ADDR} to interface ${INTF} failed."
                return
            }
        }

    fi
}

SetIpv4Address()
{
    local INTF=${1}
    local IF_INFO=${2}
    local IPV4_ADDR

    # Get the IPv4 link local address for this card
    IPV4_ADDR=$(/usr/lib/cumulus/chassis-info -4) || {
        echo "ERROR: Unable determine chassis IPv4 management address. Is this a chassis?"
        return
    }

    # Does this card have an IPv4 Link Local Address?
    if [ "${IPV4_ADDR}" != "None" ] ; then

        # Is the address already assigned?
        echo "${IF_INFO}" | /bin/grep "inet ${IPV4_ADDR}/16 scope link" || {
            # Assign the address to the interface
            /bin/ip address add ${IPV4_ADDR}/16 scope link dev ${INTF} || {
                echo "ERROR: Assigning IPv4 address ${IPV4_ADDR} to interface ${INTF} failed."
                return
            }
        }

    fi
}


# Get the name of the management interface for this chassis/card
INTF=$(/usr/lib/cumulus/chassis-info -i) || {
    echo "ERROR: Unable determine chassis management interface. Is this a chassis?"
    exit 1
}

# Use the interface name supplied as the first parameter, otherwise use default
if [ -n "$1" ] ; then
    INTF="$1"
fi

# Check if the interface exists
IF_INFO=$(/bin/ip -o address show ${INTF}) || {
    echo "ERROR: The supplied interface name, ${INTF}, does not exist."
    exit 1
}

SetIpv6Address ${INTF} ${IF_INFO}
SetIpv4Address ${INTF} ${IF_INFO}

