#!/bin/bash

set -e

typeset -r RADIUM_CONF=/run/argus/radium.conf
typeset -r CLIENT_CONF=/run/argus/radium-client.conf

if [[ -r /etc/os-release ]] ; then
	. /etc/os-release
fi

is_sensor_appliance(){
	if [[ "${QOSIENT_SYSTEM_TYPE}" == sensor \
	      || -z "${QOSIENT_SYSTEM_TYPE}" ]] ; then
		return 0;
	fi
	return 1
}

generate_monitor_id() {
	local uuid=$(dmidecode -s system-uuid)
	if [[ -z "$uuid" ]] ; then
		uuid=$(uuidgen -t)
	fi

	# uuid + interface name
	echo "${uuid}"
}

get_monitor_id() {
	local cachedir="/var/cache/argus"
	local idcache="${cachedir}/monitor-id"

	# Look for cached value.  If not found, make a new monitor
	# id and save it.
	if [[ -f $idcache ]] ; then
		cat $idcache
	else
		mkdir -p ${cachedir}
		generate_monitor_id | tee ${idcache}
	fi
}


generate_monitor_id() {
	local uuid=$(dmidecode -s system-uuid)
	if [[ -z "$uuid" ]] ; then
		uuid=$(uuidgen -t)
	fi

	# uuid + interface name
	echo "${uuid}"
}

get_monitor_id() {
	local cachedir="/var/cache/argus"
	local idcache="${cachedir}/monitor-id"

	# Look for cached value.  If not found, make a new monitor
	# id and save it.
	if [[ -f $idcache ]] ; then
		cat $idcache
	else
		mkdir -p ${cachedir}
		generate_monitor_id | tee ${idcache}
	fi
}

radium_configure(){
	echo "RADIUM_MONITOR_ID=$(get_monitor_id)"
	echo "RADIUM_MONITOR_ID_INCLUDE_INF=yes"
	echo "RADIUM_BIND_IP=::"

	# collectors and, later, distribution nodes will need this
	if ! is_sensor_appliance ; then
		echo "RADIUM_V3_ACCESS_PORT=5561"
		echo "RADIUM_MIN_SSF=1"
		echo "RADIUM_MAX_SSF=128"
		echo "RADIUM_AUTH_LOCALHOST=no"
		echo "RADIUM_CLASSIFIER_FILE=/usr/argus/ralabel.country.conf"
	fi
}

client_configure(){
	echo "RA_RELIABLE_CONNECT=yes"
}

if (( $# == 0 )) ; then
	exit 1
fi

if [[ "$1" == start ]] ; then
	mkdir -p $(dirname ${RADIUM_CONF})
	radium_configure > ${RADIUM_CONF}
	client_configure > ${CLIENT_CONF}
elif [[ "$1" == stop ]] ; then
	rm -f ${RADIUM_CONF} ${CLIENT_CONF}
fi

