#!/bin/sh

# This script is run to create persistent network device naming rules
# based on properties of the device.
# If the interface needs to be renamed, INTERFACE_NEW=<name> will be printed
# on stdout to allow udev to IMPORT it.

# variables used to communicate:
#   PCI_SLOT_NAME         The pci slot name of one virtual function inited

# Copyright (C) 2011 Li Dongyang <lidongyang@novell.com>
#
# 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, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


RULES_FILE='/etc/udev/rules.d/70-persistent-mac-vf.rules'

. /lib/udev/rule_generator.functions
. /lib/udev/vf_mac.functions

if [ -f /proc/xen/capabilities ] &&
	grep -q "control_d" /proc/xen/capabilities; then
	echo xen-dom0
else
	# Only generate rules for Xen Dom-0, or we might stall on guest below get_pf_name
	exit 0
fi

if [ -z "$PCI_SLOT_NAME" ]; then
        echo "missing \$PCI_SLOT_NAME" >&2
        exit 1
fi

if [ -e $RULES_FILE ]; then
        grep -q $PCI_SLOT_NAME $RULES_FILE
        if [ $? -eq 0 ]; then
                exit 0
        fi
fi

write_rule() {
        local pci_slot_name="$1"
        local vf_mac="$2"
        local comment="$3"

        {
        if [ "$PRINT_HEADER" ]; then
                PRINT_HEADER=
                echo "# This file was automatically generated by the $0"
                echo "# program, run by the persistent-mac-vf-generator.rules rules file."
                echo "#"
                echo "# You can modify it, as long as you keep each rule on a single"
                echo "# line, and change only the value of the MAC you want."
        fi

        echo ""
        [ "$comment" ] && echo "# $comment"
        echo "SUBSYSTEM==\"pci\", ACTION==\"change\", KERNEL==\"$pci_slot_name\", RUN+=\"set_vf_mac $pci_slot_name $vf_mac\""
        } >> $RULES_FILE
}

get_pf_name $PCI_SLOT_NAME
get_vf_id $PCI_SLOT_NAME

VF_MAC=$(ip link show $PF_INF_NAME | grep "vf $VF_ID")
VF_MAC=${VF_MAC##* }

# Prevent concurrent processes from modifying the file at the same time.
lock_rules_file

# Check if the rules file is writeable.
choose_rules_file

write_rule "$PCI_SLOT_NAME" "$VF_MAC"

unlock_rules_file

exit 0
