#!/bin/bash
# Vipweb by brain (alpha version)

# vars (in the future gen localfile with informations)

vip="172.16.48.10"
twin="192.168.0.2"
interface="ens18:web"
cidr="24"
gateway=$(/sbin/ip route | awk '/default/ { print $3 }')
option1="$1"
option2="$2"
sshport=65022


function initchecks ()
{

	localup=$(/sbin/ifconfig |grep -o "inet $vip" |cut -d " " -f2)
	remoteup=$(ssh -l root $twin -p $sshport "/sbin/ifconfig |grep -o \"inet $vip\" |cut -d \" \" -f2")

}

function checkoptions1 ()
{
	if [[ "$option1" = "down" ]]
	then
		vipdown
		exit 0
	elif [[ "$option1" = "up" ]] 
	then
		echo "Ok, I'll try..."
	else
		echo "Wrong or missing parameter: please use up or down. You can also use a second parameter yes to auto umount remote vip "
		exit 0
	fi
}

function checkoptions2 ()
{
	if [[ "$option2" = "yes" ]]
	then
		remotevipdown
	
	else
		echo "Ok, I'll just check if remote VIP $vip"
	fi
}


function checkiflocalvipup()
{

	vip=$1
	localup=$2
	text1="$3"
	text2="$4"

	if [[ "$vip" = "$localup" ]]

	then
    	echo "$text1" ; exit 0
	else
		echo "$text2"
	fi

}

function checkifremotevipup()
{

	vip=$1
	remoteup=$2
	text1="$3"
	text2="$4"

	if [[ "$vip" = "$remoteup" ]]

	then
    	echo "$text1" ; exit 0
	else
		echo "$text2"

	fi

}

function vipup()
{
	/sbin/ifconfig "$interface" "$vip/$cidr"
	arping -S "$vip" "$gateway" -c 2
}

function vipdown()
{
	/sbin/ifconfig "$interface" down
	echo "Down VIP ($vip) interface in progress..."
	sleep 2

	initchecks >/dev/null 2>&1

	if [[ "$vip" = "$localup" ]]

	then
    	echo "Error: failed to unmount the VIP $vip" ; exit 0
	else
		echo "OK: VIP $vip is not configured on this host anymore"
	fi
	echo "Down Ok"
}


function remotevipdown()
{
	ssh -l root "$twin" -p $sshport "/sbin/ifconfig "$interface" down" >/dev/null 2>&1

	echo "Down remotevip ($vip) interface in progress..."
	sleep 2

	initchecks >/dev/null 2>&1

	if [[ "$vip" = "$remoteup" ]]

	then
    	echo "ERROR: Failed to down remote vip $vip" ; exit 0
	else
		echo "Remote vip $vip now down, next step..."

	fi

}


initchecks >/dev/null 2>&1

checkoptions1

initchecks >/dev/null 2>&1

checkoptions2

checkiflocalvipup "$vip" "$localup" "VIP $vip already up, exiting..." "local VIP $vip not present, checking remote vip..." 
sleep 2

checkifremotevipup "$vip" "$remoteup" "Remote VIP $vip already up, exiting..." "Remote VIP $vip not present, next step..."
sleep 2

vipup

initchecks >/dev/null 2>&1
sleep 2

checkiflocalvipup "$vip" "$localup" "VIP now up, all is ok" "Can't mount VIP, admin need to check"
