#!/bin/bash -e

baseDir() {
	# see https://stackoverflow.com/questions/59895
	SOURCE=${BASH_SOURCE[0]}
	while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
		DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
		SOURCE=$(readlink "$SOURCE")
		[[ $SOURCE != /* ]] && SOURCE=$DIR/$SOURCE # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
	done
	DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )
	echo $DIR
}

BASE=$(baseDir)
cd $BASE

source ./lib/functions.sh

ACTION=$1
export PROJECT=$2

if [[ -z $1 || -z $2 ]]; then
	printUsage
	exit 1
fi

case "$PROJECT" in
	ccp)
		#nothing extra to do
		;;
	bbmri)
		#nothing extra to do
		;;
	cce)
		#nothing extra to do
		;;
	pscc)
		#nothing extra to do
		;;
	itcc)
		#nothing extra to do
		;;
	kr)
		#nothing extra to do
		;;
	dhki)
		#nothing extra to do
		;;
	nngm)
		#nothing extra to do
		;;
	minimal)
		#nothing extra to do
		;;
	*)
		printUsage
		exit 1
		;;
esac

# Loads config variables and runs the projects setup script
loadVars() {
	set -a
	# Source the project specific config file
	source /etc/bridgehead/$PROJECT.conf || fail_and_report 1 "/etc/bridgehead/$PROJECT.conf not found"
	# Source the project specific local config file if present
	# This file is ignored by git as oposed to the regular config file as it contains private site information like etl auth data
	if [ -e /etc/bridgehead/$PROJECT.local.conf ]; then
		log INFO "Applying /etc/bridgehead/$PROJECT.local.conf"
		source /etc/bridgehead/$PROJECT.local.conf || fail_and_report 1 "Found /etc/bridgehead/$PROJECT.local.conf but failed to import"
	fi
	# Set execution environment on main default to prod else test
	if [[ -z "${ENVIRONMENT+x}" ]]; then
		if [ "$(git rev-parse --abbrev-ref HEAD)" == "main" ]; then
			ENVIRONMENT="production"
		else
			ENVIRONMENT="test" # we have acceptance environment in BBMRI ERIC and it would be more appropriate to default to that one in case the data they have in BH is real, but I'm gonna leave it as is for backward compatibility
		fi
	fi
	# Source the versions of the images components 
	case "$ENVIRONMENT" in
		"production")
			source ./versions/prod
			;;
		"test")
			source ./versions/test
			;;
		"acceptance")
			source ./versions/acceptance
			;;
		*)
			report_error 7 "Environment \"$ENVIRONMENT\" is unknown. Assuming production. FIX THIS!"
			source ./versions/prod
			;;
	esac
	fetchVarsFromVaultByFile /etc/bridgehead/$PROJECT.conf || fail_and_report 1 "Unable to fetchVarsFromVaultByFile"
	setHostname
	optimizeBlazeMemoryUsage
	# Run project specific setup if it exists
	# This will ususally modiy the `OVERRIDE` to include all the compose files that the project depends on
	# This is also where projects specify which modules to load
	[ -e ./$PROJECT/vars ] && source ./$PROJECT/vars
	set +a

	OVERRIDE=${OVERRIDE:=""}
	# minimal contains shared components, so potential overrides must be applied in every project
	if [ -f "minimal/docker-compose.override.yml" ]; then
		log INFO "Applying Bridgehead common components override (minimal/docker-compose.override.yml)"
		OVERRIDE+=" -f ./minimal/docker-compose.override.yml"
	fi
	if [ -f "$PROJECT/docker-compose.override.yml" ]; then
		log INFO "Applying $PROJECT/docker-compose.override.yml"
		OVERRIDE+=" -f ./$PROJECT/docker-compose.override.yml"
	fi
	detectCompose
	setupProxy
}

case "$ACTION" in
	start)
		loadVars
		hc_send log "Bridgehead $PROJECT startup: Checking requirements ..."
		checkRequirements
		sync_secrets
		hc_send log "Bridgehead $PROJECT startup: Requirements checked out. Now starting bridgehead ..."
		exec $COMPOSE -p $PROJECT -f ./minimal/docker-compose.yml -f ./$PROJECT/docker-compose.yml $OVERRIDE up --abort-on-container-exit
		;;
	stop)
		loadVars
		# Kill stale secret-sync instances if present
		docker kill $(docker ps -q --filter ancestor=docker.verbis.dkfz.de/cache/samply/secret-sync-local) 2>/dev/null || true
		# HACK: This is temporarily to properly shut down false bridgehead instances (bridgehead-ccp instead ccp)
		$COMPOSE -p bridgehead-$PROJECT -f ./minimal/docker-compose.yml -f ./$PROJECT/docker-compose.yml $OVERRIDE down
		exec $COMPOSE -p $PROJECT -f ./minimal/docker-compose.yml -f ./$PROJECT/docker-compose.yml $OVERRIDE down
		;;
	is-running)
		bk_is_running
		exit $?
		;;
	logs)
		loadVars
		shift 2
		exec journalctl -u bridgehead@$PROJECT -u bridgehead-update@$PROJECT -a $@
		;;
	docker-logs)
		loadVars
		shift 2
		exec $COMPOSE -p $PROJECT -f ./minimal/docker-compose.yml -f ./$PROJECT/docker-compose.yml $OVERRIDE logs -f $@
		;;
	update)
		loadVars
		exec ./lib/update-bridgehead.sh $PROJECT
		;;
	check)
		loadVars &> /dev/null
		exec ./lib/check-bridgehead.sh $PROJECT
		;;
	install)
		source ./lib/prepare-system.sh NODEV
		loadVars
		exec ./lib/install-bridgehead.sh $PROJECT
		;;
	dev-install)
		exec ./lib/prepare-system.sh DEV
		loadVars
		exec ./lib/install-bridgehead.sh $PROJECT
		;;
	uninstall)
		exec ./lib/uninstall-bridgehead.sh $PROJECT
		;;
	adduser)
		loadVars
		log "INFO" "Adding encrypted credentials in /etc/bridgehead/$PROJECT.local.conf"
    		read -p "Please choose the component (LDM_AUTH|NNGM_AUTH|EXPORTER_USER) you want to add a user to : " COMPONENT
    		read -p "Please enter a username: " USER
    		read -s -p "Please enter a password (will not be echoed): "$'\n' PASSWORD
    		add_basic_auth_user $USER $PASSWORD $COMPONENT $PROJECT
		;;
	enroll)
		loadVars
		do_enroll $PROXY_ID
		;;
	preRun | preUpdate)
		fixPermissions
		;;
	postRun | postUpdate)
		;;
	*)
		printUsage
		exit 1
		;;
esac

exit 0
