#!/bin/bash

# Adam Wujek @ CERN
# script to assembly ppsi.conf based on dot-config configuration

PRE_FILE="/wr/etc/ppsi-pre.conf"
OUTPUT_FILE="/etc/ppsi.conf"

if [ -f /wr/etc/dot-config ]; then
    . /wr/etc/dot-config
else
    # if dot-config not available remove ppsi's config
    rm $OUTPUT_FILE
    exit 1
fi

echo "# Autogenerated file, please don't edit." > $OUTPUT_FILE
echo "# This file will be overwritten at next boot." >> $OUTPUT_FILE

#copy top of ppsi.conf
cat $PRE_FILE >> $OUTPUT_FILE

for i_zero in {01..18};do
	# unset parametes
	unset p_name
	unset p_proto
	unset p_role
	# parse parameters
	param_line=$(eval "echo \$CONFIG_PORT"$i_zero"_PARAMS")
	IFS_OLD=$IFS
	IFS=','
	# save pairs into array
	pair_array=($param_line)
	IFS=$IFS_OLD
	for pair in ${pair_array[@]}
	do
		# split pairs
		IFS='=' read param value <<< "$pair"
		case $param in
		"name")
			p_name="$value";;
		"proto")
			p_proto="$value";;
		"role")
			p_role="$value";;
		esac

	done

	# if role "none" skip port configuration
	if [ "$p_role" == "none" ]; then
		continue
	fi

	#remove leading zero from i_zero (params has numbers with leading zero,
	#interface names are without leading zero)
	i=$(expr $i_zero + 0)

	if [ -n "$p_proto" ]; then
		echo "port wri$i-$p_proto" >> $OUTPUT_FILE
		echo "proto $p_proto" >> $OUTPUT_FILE
	else
		echo "port wri$i-raw" >> $OUTPUT_FILE
	fi
	echo "iface wri$i" >> $OUTPUT_FILE
	if [ -n "$p_role" ]; then
		echo "role $p_role" >> $OUTPUT_FILE
	fi
	#hardcode whiterabbit as extension
	echo "extension whiterabbit" >> $OUTPUT_FILE

	# separate ports
	echo "" >> $OUTPUT_FILE
done

