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

initDirectory() {
	conf_file=$1

	echo "Start Directory init"
	# create default fields in conf file
	echo "Init conf file"
	3dJuumpInfiniteCli directory 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 directory conf consolidate --conf-file $conf_file
	if [ $? -ne 0 ]
	then
		exit 1
	fi
	# init directory resources
	echo "Init/Update db"
	3dJuumpInfiniteCli directory 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_directory_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_directory_data
		chgrp -R $GID /infinite_directory_data
	fi
	
	# force a quick cleanup
	echo "Run fast cleanup"
	3dJuumpInfiniteHttpServerDirectory garbagecollector --no-data-cleanup --single-run --conf-file $conf_file
	echo "Directory init done"
}

runHttpApi() {
	conf_file=$1
	echo "Start 3dJuumpInfiniteHttpServerDirectory httpserver ..."
	# use exec so we will receive signals
	exec 3dJuumpInfiniteHttpServerDirectory httpserver --conf-file $conf_file
}

runGarbageCollector() {
	conf_file=$1
	echo "Start 3dJuumpInfiniteHttpServerDirectory garbagecollector ..."
	# use exec so we will receive signals
	exec 3dJuumpInfiniteHttpServerDirectory garbagecollector --max-cleanup-workers 6 --conf-file $conf_file
}

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

# start final executable
case $CONTAINER_ROLE in
	"init")
		# this target will initialize the directory configuration only, it might be usefull to have a separate target if root rights are needed only for initialization
		initDirectory $conf_file
		;;
	"httpserver")
		# this target will run the directory http api
		runHttpApi $conf_file
		;;
	"garbagecollector")
		# this target will run the directory garbage collector
		runGarbageCollector $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

