#!/bin/sh
#
#   Copyright (c) 2014 Brocade Communications Systems, Inc.
#   All rights reserved.
#
#	File name : precfgclean
#
#	This script performs few pre-cleanup/pre-default operations on the
#	FOS Backend configurations. This script is currently being used
#	by "write erase" NOS cli.

STS_OK=0
STS_ERR=255
STS_EXIT=$STS_OK

swbd() {
	/bin/sed -n -e 's/^.*\(SWBD[[:digit:]]\{1,\}\).\+$/\1/gp'
}

SWBD=$(sin | swbd 2> /dev/null)

is_mm_system()
{
	case ${SWBD##SWBD} in
		'1000' | '1001' | '1002' | '1003')
			return 1;;
		*)
			return 0;;
	esac
}

default_mgmt_addr() {

	is_mm_system
	if [ $? -eq 1 ];then
		# Chassis based system
		$VERBOSE "Reset the Chassis addr."
		/fabos/sbin/ipaddrset -ipv4 -add -chassis -ethip none -ethmask none
		/bin/sleep 1

		$VERBOSE "Reset the Ipv4 addr of Local."
		/fabos/sbin/ipaddrset -ipv4 -add -cp 0 -ethip none -ethmask none -gwyip none
		/bin/sleep 1

		$VERBOSE "Reset the Ipv4 addr of Peer."
		/fabos/sbin/ipaddrset -ipv4 -add -cp 1 -ethip none -ethmask none -gwyip none
		/bin/sleep 1
	else
		# Pizzabox
		$VERBOSE "Reset the Ipv4 addr of switch."
		/fabos/sbin/ipaddrset -ipv4 -add -ethip none -ethmask none -dhcp off
		/bin/sleep 1
	fi

	return $STS_OK
}

default_mgmt_v6_addr() {

	is_mm_system
	if [ $? -eq 1 ];then
		# Chassis based system
		$VERBOSE "Delete the Chassis V6 addr."
		ipaddrset -ipv6 --delete -chassis
		/bin/sleep 1

		$VERBOSE "Delete the Ipv6 addr of Local."
		ipaddrset -ipv6 --delete -cp 0
		/bin/sleep 1

		$VERBOS "Delete the Ipv6 addr of peer."
		ipaddrset -ipv6 --delete -cp 1
		/bin/sleep 1
	else
		# Pizzabox
		$VERBOSE "Delete the Ipv6 addr of switch."
		ipaddrset -ipv6 --delete
		/bin/sleep 1
	fi

	return $STS_OK
}

display_usage() {
	echo "Precfgclean script"
	echo "Use this script to perform cleanup operations."
	echo "Option \'h\' to display the usage."
	echo "Option \'v\' to enable verbose mode."
	echo "Option \'i\' to default managment ip address."
}


#
# Main Routine
#
VERBOSE=:
MGMT_IP_DEF=0

while getopts vi opt; do
	case $opt in
	h)
		display_usage
		exit $STS_OK
	;;
	v)
		VERBOSE=echo
	;;
	i)
		MGMT_IP_DEF=1
	;;
	esac
done

if [ $MGMT_IP_DEF -eq 1 ]; then
	$VERBOSE "Default the management ip-address."
	default_mgmt_addr
	default_mgmt_v6_addr
	STS_EXIT=$?
fi

exit $STS_EXIT
