#! /bin/bash


RULES_FILE='/etc/udev/rules.d/70-persistent-net.rules'
OLD_RULES_FILE=/etc/udev/rules.d/30-net_persistent_names.rules
PATH='/sbin:/bin'

test -r "$OLD_RULES_FILE.to_convert" || exit 0

# Read a single line from file $1 in the $DEVPATH directory.
# The function must not return an error even if the file does not exist.
sysread() {
	local file="$1"
	[ -e "/sys$DEVPATH/$file" ] || return 0
	local value
	read value < "/sys$DEVPATH/$file" || return 0
	echo "$value"
}

sysreadlink() {
	local file="$1"
	[ -e "/sys$DEVPATH/$file" ] || return 0
	readlink -f /sys$DEVPATH/$file 2> /dev/null || true
}

# Return true if a directory is writeable.
writeable() {
	if ln -s test-link $1/.is-writeable 2> /dev/null; then
		rm -f $1/.is-writeable
		return 0
	else
		return 1
	fi
}

# Create a lock file for the current rules file.
lock_rules_file() {
	[ -e /dev/.udev/ ] || return 0

	RULES_LOCK="/dev/.udev/.lock-${RULES_FILE##*/}"

	retry=30
	while ! mkdir $RULES_LOCK 2> /dev/null; do
		if [ $retry -eq 0 ]; then
			 echo "Cannot lock $RULES_FILE!" >&2
			 exit 2
		fi
		sleep 1
		retry=$(($retry - 1))
	done
}

unlock_rules_file() {
	[ "$RULES_LOCK" ] || return 0
	rmdir $RULES_LOCK || true
}

# Choose the real rules file if it is writeable or a temporary file if not.
# Both files should be checked later when looking for existing rules.
choose_rules_file() {
	local tmp_rules_file="/dev/.udev/tmp-rules--${RULES_FILE##*/}"
	[ -e "$RULES_FILE" -o -e "$tmp_rules_file" ] || PRINT_HEADER=1

	if writeable ${RULES_FILE%/*}; then
		RO_RULES_FILE='/dev/null'
	else
		RO_RULES_FILE=$RULES_FILE
		RULES_FILE=$tmp_rules_file
	fi
	touch $RULES_FILE
}

# Return the name of the first free device.
raw_find_next_available() {
	local links="$1"

	local basename=${links%%[ 0-9]*}
	local max=-1
	for name in $links; do
		local num=${name#$basename}
		[ "$num" ] || num=0
		[ $num -gt $max ] && max=$num
	done

	local max=$(($max + 1))
	# "name0" actually is just "name"
	[ $max -eq 0 ] && return
	echo "$max"
}

# Find all rules matching a key (with action) and a pattern.
find_all_rules() {
	local key="$1"
	local linkre="$2"
	local match="$3"

	local search='.*[[:space:],]'"$key"'"\('"$linkre"'\)"[[:space:]]*\(,.*\|\\\|\)$'
	echo $(sed -n -e "${match}s/${search}/\1/p" $RO_RULES_FILE $RULES_FILE)
}

interface_name_taken() {
	local value="$(find_all_rules 'NAME=' $INTERFACE)"
	if [ "$value" ]; then
		return 0
	else
		return 1
	fi
}

find_next_available() {
	raw_find_next_available "$(find_all_rules 'NAME=' "$1")"
}

write_rule() {
	local match="$1"
	local name="$2"
	local comment="$3"

	{
	if [ "$PRINT_HEADER" ]; then
		PRINT_HEADER=
		echo "# This file was automatically generated by the $0"
		echo "# program, probably run by the persistent-net-generator.rules rules file."
		echo "#"
		echo "# You can modify it, as long as you keep each rule on a single line."
	fi

	echo ""
	[ "$comment" ] && echo "# $comment"
	echo "SUBSYSTEM==\"net\", $match, NAME=\"$name\""
	} >> $RULES_FILE
}


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

# Check if the rules file is writeable.
choose_rules_file

COMMENT="converted 'rename_netiface' rule"

while read A B C D E F X; do
	test "${A:0:5}" == "SUBSY" || continue
	test "${B:0:5}" == "ACTIO" || continue
	test "${C:0:5}" == "SYSFS" || continue
	test "${D:0:5}" == "IMPOR" || continue
	test "$E" == "%k" || continue
	INTERFACE=${F//\"/}
	MAC_ADDR=${C#*\"}
	MAC_ADDR=${MAC_ADDR%\"*}

	# If a rule using the current name already exists then find a new name and
	# report it to udev which will rename the interface.
	basename=${INTERFACE%%[0-9]*}
	if interface_name_taken; then
		INTERFACE="$basename$(find_next_available "$basename[0-9]*")"
		if [ ! -t 1 ]; then
			echo "INTERFACE_NEW=$INTERFACE"
		fi
	fi
	
	# the DRIVERS key is needed to not match bridges and VLAN sub-interfaces
	match="DRIVERS==\"?*\", ATTR{address}==\"$MAC_ADDR\""
	if [ $basename = "ath" -o $basename = "wlan" ]; then
		match="$match, ATTR{type}==\"1\"" # do not match the wifi* interfaces
	fi
	
	write_rule "$match" "$INTERFACE" "$COMMENT"

done < $OLD_RULES_FILE.to_convert
mv $OLD_RULES_FILE.to_convert $OLD_RULES_FILE.disabled

unlock_rules_file
