#!/bin/sh

TYPE=`echo ${XENBUS_PATH} | cut -f 2 -d '/'`
DOMID=`echo ${XENBUS_PATH} | cut -f 3 -d '/'`
DEVID=`echo ${XENBUS_PATH} | cut -f 4 -d '/'`

XAPI=/xapi/${DOMID}/hotplug/${TYPE}/${DEVID}

VM=$(list_domains -domid ${DOMID} -minimal)
VIF=$(xe vif-list vm-uuid=${VM} device=${DEVID} --minimal)

handle_promiscuous()
{
    local arg=$(xe vif-param-get param-name=other-config param-key=promiscuous uuid=${VIF} 2>/dev/null)
    if [ $? -eq 0 -a -n "${PROMISCUOUS}" ] ; then
        case "${arg}" in 
            true|on) echo 1 > /sys/class/net/${vif}/brport/promisc ;;
            *) echo 0 > /sys/class/net/${vif}/brport/promisc ;;
        esac
    fi
}

handle_ethtool()
{
    local opt=$1
    local arg=$(xe vif-param-get param-name=other-config param-key=ethtool-${opt} uuid=${VIF} 2>/dev/null)
    if [ $? -eq 0 -a -n "${arg}" ] ; then
        case "${arg}" in
            true|on)   /sbin/ethtool -K "${vif}" "${opt}" on ;;
            false|off) /sbin/ethtool -K "${vif}" "${opt}" off ;;
            *) logger -t scripts-vif "Unknown ethtool argument ${opt}=${arg} on ${vif}/${VIF}" ;;
        esac
    fi
}

handle_mtu()
{
    local arg=$(xe vif-param-get param-name=other-config param-key=mtu uuid=${VIF} 2>/dev/null)

    if [ -n "${arg}" ] ; then
	# test returns 2 if ${arg} is not an integer
	test "${arg}" -eq 0 2>/dev/null
	case $? in
	    0|1) echo "${arg}" > "/sys/class/net/${vif}/mtu" ;;
	    2|*) logger -t scripts-vif "Invalid MTU \`${arg}' given for ${vif}/${VIF}" ;;
	    esac
    fi
}

case "$1" in
online)
	handle_promiscuous
	handle_mtu
	handle_ethtool rx
	handle_ethtool tx
	handle_ethtool sg
	handle_ethtool tso
	handle_ethtool ufo
	handle_ethtool gso

	xenstore-write "${XAPI}/vif" "${vif}"
	xenstore-write "${XAPI}/hotplug" "online"

	;;
remove)
	xenstore-rm "${XAPI}/hotplug"
	;;
esac
