#!/bin/sh
# Custom script to maintain additional IPs

# Program development at projectes_publics/ctctl/ovh-vps/

TargetInterface=eth0
TargetPrimaryIP=1.2.3.4
TargetSecondaryIPs=""

InstalledScript=/etc/network/if-up.d/00-ovps-secondary-ips
Result=0 ; ResultN=0

if [ "$1" != "install" ] ; then
	EventInterfaces="$IFACE"
	if [ "$EventInterfaces" = "" ] ; then EventInterfaces="$DEVICE_IFACE" ; fi
	if [ "$EventInterfaces" = "--all" ] ; then
		EventInterfaces="$(/sbin/ip link show up | grep -ve '^ ' | cut -f 2 -d ':')"
	fi
	for CurInterface in $EventInterfaces ; do
		if [ "$CurInterface" = "$TargetInterface" ] ; then
#			/sbin/ip addr add $TargetPrimaryIP dev "$CurInterface" 2>/dev/null
			for CurIP in $TargetPrimaryIP $TargetSecondaryIPs ; do
				WorkingIPs="$(ip address show dev "$CurInterface" | tr -s ' ' '\n' | grep -e '..*\...*\...*\..' | cut -f 1 -d '/')"
				IpRegexp="$(printf '%s\n' "$CurIP" | sed -e 's|\.|\\.|g')"
				if [ "$(printf '%s\n' "$WorkingIPs" | grep -e "^${IpRegexp}$")" = "" ] ; then
					printf '%s\n' "Adding $CurIP to $CurInterface"
					/sbin/ip addr add ${CurIP}/32 dev "$CurInterface"
				else
					printf '%s\n' "$CurInterface has already $CurIP assigned."
				fi
			done
		fi
	done
else
	cat "$0" > "$InstalledScript"
	Result=$? ; if [ $ResultN -eq 0 ] ; then ResultN=$Result ; fi
	chmod +x "$InstalledScript"
	Result=$? ; if [ $ResultN -eq 0 ] ; then ResultN=$Result ; fi
	if [ $ResultN -eq 0 ] ; then
		printf '%s\n' "I: You may want to edit and customize file: $InstalledScript"
	fi
fi

exit $ResultN
