#!/bin/sh
# SPDX-License-Identifier: BSD-2-Clause
# SPDX-FileCopyrightText: 2016 Matt Churchyard <churchers@gmail.com>

# show the configuration details for a vale switch
#
# @param string _name the switch name
# @param string _format output format
#
switch::vale::show(){
    local _name="$1"
    local _format="$2"
    local _id

    switch::vale::id "_id" "${_name}"
    printf "${_format}" "${_name}" "vale" "${_id}" "n/a" "n/a" "n/a" "n/a" "n/a"
}

# create a vale switch
#
# @param string _switch the name of the switch
#
switch::vale::create(){

    config::core::set "switch_list" "${_switch}" "1"
    config::core::set "type_${_switch}" "vale"
}

# remove a vale switch
#
switch::vale::remove(){ }

# add a new interface to this switch
# at the moment we require the user to manually
# set up any vale switches
#
# @param string _switch name of the switch
# @param string _if the interface to add
#
switch::vale::add_member(){
    util::err "physical interfaces must be added to the vale switch manually"
}

# remove an interface
#
# @param string _switch name of the switch
# @param string _if the interface to remove
#
switch::vale::remove_member(){
    util::err "physical interfaces must be removed from the vale switch manually"
}

# set vlan id
#
# @param string _switch name of switch
# @param int _vlan vlan id to set
#
switch::vale::vlan(){
    util::err "vlan support is not currently implemented for vale switches"
}

# gets a unique port name for a vale interface
# we need to make sure vale switch name is the same
# for all interfaces on the same switch, but port is
# different
#
# @param string _var name of variable to put port name into
# @param string _switch the name of the switch
# @param string _port unique port identifier (usually mac address)
#
switch::vale::id(){
    local _var="$1"
    local _switch="$2"
    local _port="$3"
    local _id_s _id_p

    # get a switch id
    _id_s=$(md5 -qs "${_switch}" | cut -c1-5)

    # given port?
    if [ -n "${_port}" ]; then
        _id_p=$(md5 -qs "${_port}" | cut -c1-5)
        setvar "${_var}" "vale${_id_s}:${_id_p}"
    else
        setvar "${_var}" "vale${_id_s}"
    fi
}

# create a vale interface for a guest
# relies heavily on variables set in the main vm::run function
#
# @modifies _func _devices
# @return 1 if we don't get a tap device
#
switch::vale::provision(){
    local _vale_id

    # create a vale port id
    switch::vale::id "_vale_id" "${_switch}" "${_mac}"

    util::log "guest" "${_name}" "adding vale interface ${_tap} (${_switch})"
    _devices="${_devices} -s ${_bus}:${_slot}:${_func},${_emulation},${_vale_id}"
    [ -n "${_mac}" ] && _devices="${_devices},mac=${_mac}"

    _func=$((_func + 1))
}
