#!/bin/bash
################################################################################
# Copyright 2022 ModalAI Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# 4. The Software is used solely in conjunction with devices provided by
#    ModalAI Inc.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
################################################################################

ISINSTALLED=false # set to true once we detect if docker is installed

print_usage () {
	echo ""
	echo "Start wizard with prompts:"
	echo "voxl-configure-docker-support"
	echo ""
	echo "Shortcut configuration arguments for scripted setup."
	echo "all factory options also remove any user"
	echo "customizations to /etc/modalai/docker-autorun-script.sh"
	echo ""
	echo "factory_disable - disable docker-daemon & docker-autorun"
	echo "disable         - disable docker-daemon & docker-autorun"
	echo "factory_enable  - enables docker-daemon & docker-autorun"
	echo "enable          - enables docker-daemon & docker-autorun"
	echo "install         - install docker-ce only"
	echo ""
	echo "voxl-configure-docker-support factory_disable"
	echo "voxl-configure-docker-support disable"
	echo "voxl-configure-docker-support factory_enable"
	echo "voxl-configure-docker-support enable"
	echo "voxl-configure-docker-support install"
	echo ""
	echo "show this help message:"
	echo "voxl-configure-docker-support help"
	echo ""
	exit 0
}


install_docker () {

	if $ISINSTALLED; then
		echo "Docker already installed"
		return;
	fi

	# sudo apt remove docker docker-engine docker.io containerd runc
	# sudo apt update
	# sudo apt install -y docker-ce docker-ce-cli containerd.io

	cd /tmp/
	curl -fsSL https://get.docker.com -o get-docker.sh
	sh get-docker.sh

	if [ ! -f /usr/bin/docker ]; then
		echo ""
		echo "failed to install docker"
		exit 1
	fi

	ISINSTALLED=true
	load_hello_world
}

enable_docker () {
	if ! $ISINSTALLED; then
		echo "Not enabling docker, must be installed first"
		echo "make sure you have an internet connection and run:"
		echo "voxl-configure-docker-support install"
		exit 1
	fi

	echo "--------------------------------------------------"
	echo "enabling docker service"
	echo "--------------------------------------------------"
	systemctl enable docker
	systemctl start docker

}

disable_docker () {
	if ! $ISINSTALLED; then
		echo "docker not installed, no need to disable"
		return
	fi

	echo "disabling docker service"
	systemctl disable docker
	systemctl stop docker

}

enable_docker_autorun () {
	if ! $ISINSTALLED; then
		echo "Not enabling docker-autorun, docker must be installed first"
		echo "make sure you have an internet connection and run:"
		echo "voxl-configure-docker-support install"
		exit 1
	fi

	if ! [ -f "/etc/modalai/docker-autorun-script.sh" ]; then
		echo "Copying default docker-autorun-script.sh to /etc/modalai/"
		cp /usr/share/modalai/docker-autorun-script.sh /etc/modalai/
	fi

	load_hello_world
	echo "--------------------------------------------------"
	echo "enabling docker-autorun"
	echo "--------------------------------------------------"
	systemctl enable docker-autorun
	systemctl start docker-autorun

}

disable_docker_autorun () {
	echo "--------------------------------------------------"
	echo "disabling docker-autorun"
	echo "--------------------------------------------------"
	systemctl disable docker-autorun
	systemctl stop docker-autorun
}

wipe_config () {
	rm -f /etc/modalai/docker-autorun-script.sh
	echo "Copying default docker-autorun-script.sh to /etc/modalai/"
	mkdir -p /etc/modalai/
	cp /usr/share/modalai/docker-autorun-script.sh /etc/modalai/
}


load_hello_world () {

	if ! $ISINSTALLED; then
		echo ""
		echo "can't load hello_world docker image, docker must be installed first"
		echo "make sure you have an internet connection and run:"
		echo "voxl-configure-docker-support install"
		exit 1
	fi

	# make sure docker is enabled to load the image
	enable_docker

	if docker images | grep -q "hello-image" ; then
		echo "--------------------------------------------------"
		echo "detected hello-world docker image already loaded"
		echo "you can test by running:"
		echo "voxl-docker -n -i hello-image -e \"\""
		echo "--------------------------------------------------"
		return
	fi

	## load the hello-world docker image, required for prepare-docker
	echo "--------------------------------------------------"
	echo "loading hello-world docker image"
	echo "--------------------------------------------------"
	set +e
	for i in {1..10}; do
		sleep 1
		# we expect this to fail! so set +e and redirect output to dev null
		/usr/bin/docker load -i /usr/share/modalai/docker-hello-image.tgz > /dev/null 2>&1

		if [[ "$?" == "0"* ]]; then
			break
		fi

	done

	if [ "$?" != "0" ]; then
		echo "docker daemon didn't start, try rebooting and try again"
		exit 1
	fi


	set -e

	echo "--------------------------------------------"
	echo "successfully loaded hello-world docker image"
	echo "you can test by running:"
	echo "voxl-docker -n -i hello-image -e \"\""
	echo "--------------------------------------------"
}


################################################################################
## actual start of execution, handle optional arguments first
################################################################################

## sanity checks
if ! [ $(whoami) == "root" ]; then
	echo "Please run this script as root"
	exit 1
fi



## check if docker is installed
if [ -f /usr/bin/docker ]; then
	ISINSTALLED=true
fi


## convert argument to lower case for robustness
arg=$(echo "$1" | tr '[:upper:]' '[:lower:]')

## parse arguments
case ${arg} in
	"")
		echo "Starting Wizard"
		;;
	"h"|"-h"|"help"|"--help")
		print_usage
		exit 0
		;;
	"factory_disable")
		wipe_config
		disable_docker
		disable_docker_autorun
		exit 0
		;;
	"disable")
		disable_docker
		disable_docker_autorun
		exit 0
		;;
	"factory_enable")
		wipe_config
		enable_docker
		enable_docker_autorun
		exit 0
		;;
	"enable")
		enable_docker
		enable_docker_autorun
		exit 0
		;;
	"install")
		install_docker
		exit 0
		;;
	*)
		echo "invalid option"
		print_usage
		exit 1
esac



################################################################################
## no optional arguments, start config wizard prompts
################################################################################


## check if docker is installed
if ! $ISINSTALLED; then

	echo " "
	echo "docker-ce is not currently installed."
	echo "Do you want to install docker-ce from the official docker repo?"
	echo "This requires a working internet connection."
	select opt in "yes" "no"; do
	case $opt in
	yes )
		install_docker
		break;;
	no )
		echo "Exiting config wizard"
		exit 0
		break;;
	*)
		echo "invalid option"
		esac
	done
else
	echo "detected docker-ce is already installed"
fi



# ask if the user wants the service enabled or not
echo " "
echo "Do you want to enable the docker daemon?"
select opt in "yes" "no"; do
case $opt in
yes )
	enable_docker
	break;;
no )
	disable_docker
	disable_docker_autorun
	break;;
*)
	echo "invalid option"
	esac
done

# ask if the user wants the service enabled or not
echo " "
echo "Do you want to enable the modalai docker-autorun systemctl service?"
echo "this will let you configure a docker image to load on boot using"
echo "the user-configurable /etc/modalai/docker-autorun.sh file"
DID_ENABLE=false
select opt in "yes" "no"; do
case $opt in
yes )
	enable_docker_autorun
	DID_ENABLE=true
	break;;
no )
	disable_docker_autorun
	break;;
*)
	echo "invalid option"
	esac
done

if $DID_ENABLE; then
	# ask if the user wants to factory reset the autorun config script
	echo " "
	echo "Do you want to wipe the /etc/modalai/docker-autorun-script.sh file"
	echo "back to factory default?"
	select opt in "yes" "no"; do
	case $opt in
	yes )
		wipe_config
		break;;
	no )
		break;;
	*)
		echo "invalid option"
		esac
	done
fi

echo ""

echo "--------------------------------------------"
echo ""
echo "done configuring docker support"
echo "you can test by running:"
echo "voxl-docker -n -i hello-image -e \"\""
echo ""

exit 0


