#!/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
		;;
	minimal)
		#nothing extra to do
		;;
	*)
		printUsage
		exit 1
		;;
esac

loadVars() {
	# Load variables from /etc/bridgehead and /srv/docker/bridgehead
	set -a
	source /etc/bridgehead/$PROJECT.conf || fail_and_report 1 "/etc/bridgehead/$PROJECT.conf not found"
	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
	fetchVarsFromVaultByFile /etc/bridgehead/$PROJECT.conf || fail_and_report 1 "Unable to fetchVarsFromVaultByFile"
	setHostname
	optimizeBlazeMemoryUsage
	[ -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

	# Set some project-independent default values
	: ${ENVIRONMENT:=production}

	case "$ENVIRONMENT" in
		"production")
			export FOCUS_TAG=main
			;;
		"test")
			export FOCUS_TAG=develop
			;;
		*)
			report_error 7 "Environment \"$ENVIRONMENT\" is unknown. Assuming production. FIX THIS!"
			export FOCUS_TAG=main
			;;
	esac
}

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
		# 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 $COMPOSE -p $PROJECT -f ./minimal/docker-compose.yml -f ./$PROJECT/docker-compose.yml $OVERRIDE logs -f $@
		;;
	update)
		loadVars
		exec ./lib/update-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) 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
