#!/bin/bash

# Helper for VRF devices. Call additional commands
# to handle local configuration needs.

PROG=${0##*/}
VERBOSE=0

DNS_HELPER=/usr/lib/vrf/vrf-dns-helper

################################################################################
# usage

function usage
{
	cat <<EOF
    $PROG create <vrf> <table> [boot]
    $PROG delete <vrf> <table>
    $PROG verify [<vrf> <table>]
EOF
}

################################################################################
# logging

function log_cmd
{
	if [ $VERBOSE -eq 1 ]; then
		echo "$PROG: $*"
	fi
}

################################################################################
# delete - inverse of create steps

function delete_cmd
{
	local vrf=$1
	local tbid=$2

	if [ -z "$tbid" ]; then
		usage
		return 1
	fi

	# remove per-VRF DNS config
	if [ -x ${DNS_HELPER} ]; then
		log_cmd "${DNS_HELPER} ${VERBARG} delete ${vrf} ${tbid}"
		${DNS_HELPER} ${VERBARG} delete ${vrf} ${tbid}
	fi

	log_cmd "vrf ${VERBARG} teardown ${vrf} ${tbid}"
	vrf ${VERBARG} teardown ${vrf} ${tbid}
}

################################################################################
# called on VRF create

function create_cmd
{
	local vrf=$1
	local tbid=$2
	local mode=$3    # optional arg

	if [ -z "$tbid" ]; then
		usage
		return 1
	fi
	if [ -n "$mode" -a "$mode" != "boot" ]; then
		usage
		return 1
	fi

	# local VRF configurations - if these fail caller needs to fail
	# the creation of the VRF
	log_cmd "vrf ${VERBARG} configure ${vrf} ${tbid} ${mode}"
	vrf ${VERBARG} configure ${vrf} ${tbid} ${mode} || return 1

	#
	# the rest are best effort with logging of errors
	#

	# per VRF DNS setup
	if [ -x ${DNS_HELPER} ]; then
		log_cmd "${DNS_HELPER} ${VERBARG} create ${vrf} ${tbid}"
		${DNS_HELPER} ${VERBARG} create ${vrf} ${tbid}
	fi
}

################################################################################
# run verify for each command we run

function verify_cmd
{
	local vrf=$1
	local tbid=$2
	local rc=0

	echo "vrf verify:"
	vrf verify $vrf $tbid
	[ $? -ne 0 ] && rc=1

	if [ -x ${DNS_HELPER} ]; then
		echo
		echo "${DNS_HELPER##*/} verify:"
		${DNS_HELPER} verify $vrf $tbid
		[ $? -ne 0 ] && rc=1
	fi

	return $rc
}

################################################################################
# main

# enable verbose logging?
if [ "$1" = "-v" ]; then
	VERBOSE=1
	VERBARG="-v"
	shift
fi

CMD=$1
shift
case "$CMD" in
	create) create_cmd $*;;
	delete) delete_cmd $*;;
	verify) verify_cmd $*;;
	*) usage; exit 1;;
esac
