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

#
# Run Script for AURA Engine
#
# Call with one of these parameters:
#
# - engine
# - test
# - recreate-database

# - docker:engine
# - docker:build
# - docker:push
# 

if [[ $* =~ ^(engine|test|recreate-database)$ ]]; then
	mode=$1 
fi

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


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


# Check for the correct Python version (3.8+)
PYTHON_EXEC="python3"
echo "[ Using $(python3 -V) ]"


# +++ DEFAULT COMMANDS +++ #

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

	### Runs Engine ###

	if [[ $mode == "engine" ]]; then
		/usr/bin/env $PYTHON_EXEC run.py
	fi

	### Runs Tests ###

	if [[ $mode == "test" ]]; then
		/usr/bin/env $PYTHON_EXEC -m unittest discover tests
	fi

	### CAUTION: This deletes everything in your database ###

	if [[ $mode == "recreate-database" ]]; then
		/usr/bin/env $PYTHON_EXEC run.py --recreate-database
	fi

fi


# +++ DOCKER COMMANDS +++ #

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

	### Runs Engine Core & Liquidsoap ###

	if [[ $mode == "engine" ]]; then

		if [[ -z "${AURA_ENGINE_CONFIG_PATH}" ]]; then
			AURA_ENGINE_CONFIG_PATH="$BASE_DIR/config/engine.docker.ini"
		fi

		if [[ -z "${AURA_ENGINE_SOCKET_DIR}" ]]; then
			AURA_ENGINE_SOCKET_DIR="$BASE_DIR/../engine-core/socket"
		fi

		if [[ -z "${AURA_ENGINE_AUDIO_SOURCE_DIR}" ]]; then
			AURA_ENGINE_AUDIO_SOURCE_DIR="$BASE_DIR/audio/source"
		fi

		if [[ -z "${AURA_ENGINE_AUDIO_PLAYLIST_DIR}" ]]; then
			AURA_ENGINE_AUDIO_PLAYLIST_DIR="$BASE_DIR/audio/playlist"
		fi

		exec sudo docker run \
			--network="host" \
			--name aura-engine \
			--rm \
			-u $UID:$GID \
			-v "$AURA_ENGINE_CONFIG_PATH":"/srv/config/engine.ini":ro \
			-v "$AURA_ENGINE_SOCKET_DIR":"/srv/socket" \
			-v "$AURA_ENGINE_AUDIO_SOURCE_DIR":"/var/audio/source":ro \
			-v "$AURA_ENGINE_AUDIO_PLAYLIST_DIR":"/var/audio/playlist" \
			-v "$BASE_DIR/logs":"/srv/logs" \
			autoradio/engine
	fi

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

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

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

	if [[ $mode == "push" ]]; then
		exec sudo docker push autoradio/engine
	fi
fi