#!/bin/sh -e
#
# Copyright (c) 2020, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation version 2 of the License.
#
# This script is run to detect the role of failover network device
# so as to define naming rules based on properties of the device.

get_drvname() {
	basename "$(readlink "${1}/device/driver")"
}

has_standby() {
	features=$(cat "${1}/device/features")
	# check if standby feature bit is enabled
	[ "$(awk 'BEGIN{print substr("'"$features"'", 63, 1)}')" = "1" ]
}

# debug, if UDEV_LOG=<debug>
if [ -n "$UDEV_LOG" ]; then
	if [ "$UDEV_LOG" -ge 7 ]; then
		set -x
	fi
fi
if [ -z "$INTERFACE" ]; then
	exit 1
fi

devpath="/sys/class/net/$INTERFACE"
if [ ! -d "$devpath" ] || [ ! -d "${devpath}/device" ]; then
	exit 1
fi

if [ "$(get_drvname "$devpath")" = virtio_net ] && has_standby "$devpath"; then
	if [ -d "${devpath}/master" ]; then
		echo 3 # Failover standby
	else
		echo 1 # Failover master
	fi
	exit 0
fi
if [ -d "${devpath}/master" ] &&
   [ "$(get_drvname "${devpath}/master")" = virtio_net ] &&
   has_standby "${devpath}/master"; then
	echo 2 # Failover primary
else
	echo 0 # Non-failover
fi
exit 0
