#!/bin/bash
#
# This wrapper script takes the environment variables currently set by
# Eric's jenkins scripts and puts everything into the config file.
# 

set -- `getopt v $*`
opt_verbose=''

function usage {

	cat >&2 <<-EOF
	Usage:
	$cmd [-v] template config-path
EOF
	exit 1
}

cmd=$0
while [ $# -gt 0 ]; do
	arg=$1; shift
	case $arg in
	--)	break;;
	-v)	opt_verbose=yes;;
	*)	echo "Unsupported argument $arg" >&2
		usage;;
	esac
done

if [ $# -ne 2 ]; then
	echo "Missing argument(s)" >&2
	usage
fi

nodes_file=$1
TWOPENCE_CONFIG_PATH=$2

cp /dev/null $TWOPENCE_CONFIG_PATH
export TWOPENCE_CONFIG_PATH

function set_group_attr_from_shellvar {

	group_path=$1
	attrname=$2
	shellvar=$3

	eval value=\"\$$shellvar\"
	if [ -n "$value" -a "$value" != "N/A" ]; then
		# echo "Set attr $group_path $attrname=$value"
		susetest config set-attr --group "$group_path" $attrname="$value"
	fi
}

function set_node_attr_from_shellvar {

	node=$1; shift
	set_group_attr_from_shellvar "/node=$node" "$@"
}

function set_network_attr_from_shellvar {

	network=$1; shift
	set_group_attr_from_shellvar "/network=$network" "$@"
}

for var in ${!SUBNET_IP_*}; do
	NETWORK=${var#SUBNET_IP_}
	network=`echo $NETWORK | tr A-Z a-z`

	susetest config add-group network=$network

	set_network_attr_from_shellvar $network ipv4_subnet SUBNET_IP_$NETWORK
	set_network_attr_from_shellvar $network ipv4_gateway GATEWAY_IP_$NETWORK
done

nodes=`sed -r 's/^node[[:space:]]+(.*)/\1/;t;d' $nodes_file`

for node in $nodes; do
	susetest config add-group node=$node

	NODE=`echo $node|tr a-z A-Z`

	set_node_attr_from_shellvar "$node" target TARGET_$NODE

	set_node_attr_from_shellvar "$node" ipaddr INTERNAL_IP_$NODE
	set_node_attr_from_shellvar "$node" ipv4_addr INTERNAL_IP_$NODE
	set_node_attr_from_shellvar "$node" ipv4_addr_ext EXTERNAL_IP_$NODE

	set_node_attr_from_shellvar "$node" ipv6_addr INTERNAL_IP6_$NODE

	set_node_attr_from_shellvar "$node" system SYSTEM_$NODE

	eval network_vars=\"\${!NETWORK_${NODE}_*}\"
	for var in $network_vars; do
		IFNAME=${var##*_}
		ifname=`echo $IFNAME | tr A-Z a-z`

		susetest config add-group --group "/node=$node" interface=$ifname
		set_group_attr_from_shellvar "/node=$node/interface=$ifname" network $var
		set_group_attr_from_shellvar "/node=$node/interface=$ifname" ipv4_addr INTERNAL_IP_${NODE}_${IFNAME}
	done

	target=`susetest config get-attr --group "/node=$node" target`
	if [ -z "$target" ]; then
		echo "No twopence target for node \"$node\"" >&2
		exit 1
	fi
done

if [ -n "$WORKSPACE" ]; then
	susetest config set-attr workspace="$WORKSPACE"
	susetest config set-attr report="$WORKSPACE/junit-results.xml"
fi

if [ -n "$opt_verbose" ]; then
	echo "== Configuration file =="
	cat $TWOPENCE_CONFIG_PATH
	echo "== ... =="
fi
