#!/bin/bash

function exec_cmd()
{
	echo "executing $@"
	$@

	if [ $? -ne 0 ]; then
		echo "Failed to execute $@"
		exit 1
	fi
}

function install_bbfdm()
{
	[ -d "/opt/dev/bbfdm" ] && return 0

	if [ -n "${BBFDM_BRANCH}" ]; then
		export BRANCH="${BBFDM_BRANCH}"
		exec_cmd git clone -b ${BBFDM_BRANCH} https://dev.iopsys.eu/bbf/bbfdm.git /opt/dev/bbfdm
	else
		exec_cmd git clone https://dev.iopsys.eu/bbf/bbfdm.git /opt/dev/bbfdm
	fi

	cd /opt/dev/bbfdm
	./gitlab-ci/install-dependencies.sh install
	./gitlab-ci/setup.sh install
}

function install_tr104_as_bbfdm_plugin()
{
	CMAKE_OPTIONS="-DBBF_VENDOR_PREFIX:String=X_IOWRT_EU_ \
		-DDAEMON_JSON_INPUT:String=/etc/tr104/input.json \
		-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON \
		-DDM_ENABLE_UBUS:BOOL=ON \
		-DTR104_EXTENSION_DIR:String=iowrt \
		-DRUNAS_BBFDM_MICROSERVICE:BOOL=ON"

	export CFLAGS="-I/usr/include/libbbfdm-api -Wall"

	[ -d "./build" ] && rm -rf build

	mkdir -p build
	cd build

	cmake ${CMAKE_OPTIONS} ..

	cd libdm
	exec_cmd make

	mkdir -p /usr/share/bbfdm/micro_services/core/

	echo "Installing tr104 as bbfdm plugins ..."
	exec_cmd cp tr104/libtr104.so /usr/share/bbfdm/micro_services/core/20_tr104.so

	echo "Installing tr104 datamodel extension as bbfdm plugins ..."
	exec_cmd cp extensions/iowrt/libtr104ext.so /usr/share/bbfdm/micro_services/core/21_tr104ext.so

	cd ../..
}
