# Neutron Cisco plugin
# ---------------------------

# Save trace setting
CISCO_XTRACE=$(set +o | grep xtrace)
set +o xtrace

# Name of cisco router plugin
Q_CISCO_ROUTER_PLUGIN=${Q_CISCO_ROUTER_PLUGIN:-}

# Specify if tunneling is enabled
Q_CISCO_PLUGIN_ENABLE_TUNNELING=${Q_CISCO_PLUGIN_ENABLE_TUNNELING:-True}

# Specify the VXLAN range
Q_CISCO_PLUGIN_VXLAN_ID_RANGES=${Q_CISCO_PLUGIN_VXLAN_ID_RANGES:-5000:10000}

# Specify the VLAN range
Q_CISCO_PLUGIN_VLAN_RANGES=${Q_CISCO_PLUGIN_VLAN_RANGES:-vlan:1:4094}

# Specify ncclient package information
NCCLIENT_DIR=$DEST/ncclient
NCCLIENT_VERSION=${NCCLIENT_VERSION:-0.3.1}
NCCLIENT_BRANCH=${NCCLIENT_BRANCH:-master}

# This routine put a prefix on an existing function name
function _prefix_function {
    declare -F $1 > /dev/null || die "$1 doesn't exist"
    eval "$(echo "${2}_${1}()"; declare -f ${1} | tail -n +2)"
}

function _has_cisco_router_plugin {
    if [[ "$Q_CISCO_ROUTER_PLUGIN" != "" ]]; then
        return 0
    fi
    return 1
}

# Check the version of the installed ncclient package
function check_ncclient_version {
python << EOF
version = '$NCCLIENT_VERSION'
import sys
try:
    import pkg_resources
    import ncclient
    module_version = pkg_resources.get_distribution('ncclient').version
    if version != module_version:
        sys.exit(1)
except:
    sys.exit(1)
EOF
}

# Install the ncclient package
function install_ncclient {
    sudo -E pip install ncclient
}

# Check if the required version of ncclient has been installed
function is_ncclient_installed {
    # Check if the Cisco ncclient repository exists
    if [[ ! -d $NCCLIENT_DIR ]]; then
        return 1
    fi
    # Check if the ncclient is installed with the right version
    if ! check_ncclient_version; then
        return 1
    fi

    return 0
}

function _configure_cisco_router_plugin {
    # Install a known compatible ncclient from the Cisco repository if necessary
    if ! is_ncclient_installed; then
        install_ncclient
    fi
}

function net_neutron_plugin_configure_service {
    local cisco_cfg_file
    cisco_cfg_file=/$Q_PLUGIN_CONF_FILE

    if _has_cisco_router_plugin; then
        _configure_cisco_router_plugin
    fi
}

# Restore xtrace 
$XTRACE 
