#!/bin/bash
mode="core"
docker="false"

#
# Run Script for AURA Engine
#
# Call with one of these parameters:
#
# - core
# - debug
# - log

# - docker:core
# - docker:debug
# - docker:build
# - docker:push
#

if [[ $* =~ ^(core|debug|log)$ ]]; then
	mode=$1
fi

if [[ "$1" == *"docker:"* ]]; then
	docker="true"
	mode=${1#*:}
fi


echo "[ Run mode=$mode ]"
echo "[ Docker=$docker ]"



# +++ DEFAULT COMMANDS +++ #

if [[ $docker == "false" ]]; then

	### Runs Engine Core (Liquidsoap) ###

	if [[ $mode == "core" ]]; then
		(cd src && liquidsoap ./engine.liq)
	fi

	### Runs Engine Core (Verbose & debug output) ###

	if [[ $mode == "debug" ]]; then
		(cd src && liquidsoap  --verbose --debug ./engine.liq)
	fi

	### Tails the log file only (Used for Docker debugging) ###

	if [[ $mode == "log" ]]; then
		tail -f logs/engine-core.log
	fi
fi


# +++ DOCKER COMMANDS +++ #

if [[ $docker == "true" ]]; then
	BASE_DIR=$(readlink -f .)
	AUDIO_DIR=$(readlink -f ./audio)
	echo "Absolute base dir: " $BASE_DIR
	echo "Absolute audio dir: " $AUDIO_DIR

	### Runs Engine Core ###

	if [[ $mode == "core" ]]; then
		exec sudo docker run \
			--network="host" \
			--name aura-engine-core \
			--rm \
			-u $UID:$GID \
			-v "$BASE_DIR/config/engine-core.docker.ini":"/srv/config/engine-core.ini":ro \
			-v "$BASE_DIR/socket":"/srv/socket" \
			-v "$AUDIO_DIR/source":"/var/audio/source":ro \
			-v "$AUDIO_DIR/playlist":"/var/audio/playlist":ro \
			-v "$AUDIO_DIR/station":"/var/audio/station":ro \
			-v "$BASE_DIR/logs":"/srv/logs" \
			--mount type=tmpfs,destination=/tmp \
			--device /dev/snd \
			--group-add audio \
			autoradio/engine-core
	fi

	### Debugging mode: only tails the log file and enter the container manually ###

	if [[ $mode == "debug" ]]; then
		exec sudo docker run \
			--network="host" \
			--name aura-engine-core \
			--rm \
			-u $UID:$GID \
			-v "$BASE_DIR/config/engine-core.docker.ini":"/srv/config/engine-core.ini":ro \
			-v "$BASE_DIR/socket":"/srv/socket" \
			-v "$AUDIO_DIR/source":"/var/audio/source":ro \
			-v "$AUDIO_DIR/playlist":"/var/audio/playlist":ro \
			-v "$AUDIO_DIR/station":"/var/audio/station":ro \
			-v "$BASE_DIR/logs":"/srv/logs" \
			--mount type=tmpfs,destination=/tmp \
			--device /dev/snd \
			--group-add audio \
			autoradio/engine-core log
	fi

	### Create Docker Image from local project ###

	if [[ $mode == "build" ]]; then
		docker build -t autoradio/engine-core .
	fi

	### Pushes the latest Docker Image to Docker Hub ###

	if [[ $mode == "push" ]]; then
		docker push autoradio/engine-core
	fi
fi