#!/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
LastStatus=0
StatusCode=0

if [ "$1" != "install" ] ; then
	EventInterfaces="$IFACE"
	if [ "$EventInterfaces" = "" ] ; then EventInterfaces="$DEVICE_IFACE" ; fi
	if [ "$EventInterfaces" = "--all" ] || [ "${EventInterfaces}${1}" = "--all" ] ; then
		EventInterfaces="$(/sbin/ip link show up | grep -ve '^ ' | cut -f 2 -d ':')"
	fi
	if [ "$EventInterfaces" = "" ] ; then
		printf '%s\n' "No IFACE triggered action."
		printf '%s\n' "You can manually specify --all to force action."
	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"
	LastStatus=$? ; if [ $StatusCode -eq 0 ] ; then StatusCode=$LastStatus ; fi
	chmod +x "$InstalledScript"
	LastStatus=$? ; if [ $StatusCode -eq 0 ] ; then StatusCode=$LastStatus ; fi
	echo '#!/bin/sh' > /etc/cron.daily/ovps-secondary-ips
	LastStatus=$? ; if [ $StatusCode -eq 0 ] ; then StatusCode=$LastStatus ; fi
	echo "echo Re-check and assign IP addresses if VPS lossed them" >> /etc/cron.daily/ovps-secondary-ips
	echo "$InstalledScript --all" >> /etc/cron.daily/ovps-secondary-ips
	LastStatus=$? ; if [ $StatusCode -eq 0 ] ; then StatusCode=$LastStatus ; fi
	chmod +x /etc/cron.daily/ovps-secondary-ips
	LastStatus=$? ; if [ $StatusCode -eq 0 ] ; then StatusCode=$LastStatus ; fi
	if [ $StatusCode -eq 0 ] ; then
		printf '%s\n' "I: You may want to edit and customize file: $InstalledScript"
	fi
fi

exit $StatusCode
