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

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

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

if [[ $* =~ ^(init|env|engine|core|lqs)$ ]]; then 
	mode=$1 
fi

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


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


# Find the correct Python version (3.8 or 3.9)

if hash python3.9 2>/dev/null; then
	PYTHON_EXEC="python3.9"
	echo "[ Using Python 3.9 ]"
else
	PYTHON_EXEC="python3.8"
	echo "[ Using Python 3.8 ]"
fi


# +++ DEFAULT COMMANDS +++ #

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

	### Initializes the environment & installs dependencies ###

	if [[ $mode == "init" ]]; then
		mkdir -p logs
		pip3 install -r requirements.txt 
	fi

	### Runs Engine Core & Liquidsoap ###

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

	### Runs Engine Core only ###

	if [[ $mode == "core" ]]; then
		/usr/bin/env $PYTHON_EXEC run.py --without-lqs
	fi

	### Runs Liquidsoap only ###

	if [[ $mode == "lqs" ]]; then
		lqs=$(/usr/bin/env $PYTHON_EXEC run.py --get-lqs-command)
		eval "$lqs"
	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_D=$(realpath "${BASH_SOURCE%/*}/")

	### Runs Engine Core & Liquidsoap ###

	if [[ $mode == "engine" ]]; then
		exec sudo docker run \
			--network="host" \
			--name aura-engine \
			--rm -d \
			-u $UID:$GID \
			-v "$BASE_D":/srv \
			-v "$BASE_D/audio/source":/var/audio/source:ro \
			-v "$BASE_D/config/docker":/etc/aura \
			-v "/dev/snd":/dev/snd \
			--privileged \
			--tmpfs /var/log/aura/ \
			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