#!/bin/sh
# exit in case of error
set -e

initProxy() {
	conf_file=$1
	echo "Start Proxy init"
	# create default fields in conf file
	echo "Init conf file"
	3dJuumpInfiniteCli proxy conf init --conf-file $conf_file
	if [ $? -ne 0 ]
	then
		exit 1
	fi
	# validate conf file and encrypt sensitive values
	echo "Consolidate conf file"
	3dJuumpInfiniteCli proxy conf consolidate --conf-file $conf_file
	if [ $? -ne 0 ]
	then
		exit 1
	fi
	# init proxy resources
	echo "Init/Update db"
	3dJuumpInfiniteCli proxy init --pg-wait-timeout 60 --conf-file $conf_file
	if [ $? -ne 0 ]
	then
		exit 1
	fi

	# if GID was changed fix permissions on data volume, by default docker volume is own by root
	if [ "$(stat -c %g /infinite_proxy_data)" != "$GID" ]; then
		echo "Fixing permissions on data volume with GID $GID, this migth take some time"
		# allow group to read/write, especially usefull if someone change running user
		chmod -R g+rwx /infinite_proxy_data
		chgrp -R $GID /infinite_proxy_data
	fi

	echo "Proxy init done"
}

runProxy() {
	conf_file=$1
	echo "Start 3dJuumpInfiniteProxyService ..."
	# use exec so we will receive signals
	exec /usr/lib/3djuump-infinite-proxy/bin/3dJuumpInfiniteProxyService run --conf-file $conf_file
}

conf_file="/etc/3djuump-infinite-proxy/conf_4_1.json"
echo "Conf file location : $conf_file"

# start final executable
case $CONTAINER_ROLE in
	"init")
		# this target will initialize the proxy configuration only, it might be usefull to have a separate target if root rights are needed only for initialization
		initProxy $conf_file
		;;
	"service")
		# this target will run the proxy service
		runProxy $conf_file
		;;
	"sleep")
		echo "Time to sleep zzzz ..."
		# use exec so we will receive signals
		exec sleep 500000000000000000000000000000000000000
		;;
	*)
		echo "CONTAINER_ROLE env should set to a correct value !"
		exit 1
esac