#!/usr/bin/env bash

INSTALL_CONFIG_FILE="/home/pi/luniebox/config/install.cfg"
REPO_URL="https://git.bstly.de/Lurkars/luniebox.git"
AUTOMATIC=false
NO_UPDATES=false
NO_SPOTIFYDL=false
NO_SPOTIFY=false
NO_MPD=false
NO_AUDIO=false
NO_MPU=true
AUDIO_DEVICE=false
AUDIO_DEVICES=("pimoroni" "adafruit")
DEVICE_NAME=false
REBOOT=false

help() {
	local IFS="|"
	printf "Usage: ${SCRIPTNAME} [-h] [-a] [--audio-device AUDIO_DEVICE] [--device-name DEVICE_NAME] [--no-updates] [--no-spotifydl] [--no-spotify] [--no-mpd] [--mpu] [--repo-url] \n"
	printf " -h\t\t\t\tshow this help\n"
	printf " -a\t\t\t\tautomatic/non-interactive mode (without --audio-device, no Audio device is set up)\n"
	printf " --audio-device [AUDIO_DEVICE]\tset Audio device (one of [${AUDIO_DEVICES[*]}])\n"
	printf " --device-name [DEVICE_NAME]\tset luniebox device name (default: luniebox)\n"
	printf " --no-updates\t\t\tskip system updates \n"
	printf " --no-spotifydl\t\t\tskip installation of zspotify (no offline support for Spotify) \n"
	printf " --no-mpd\t\t\tskip installation of Music Player Daemon (no offline support, also skips zspotify)\n"
	printf " --no-spotify\t\t\tskip installation of spotifyd (no Spotify support, also skips zspotify)\n"
	printf " --mpu\t\t\t\tsetup MPU9250 on I2C port (default is no MPU9250)\n"
	printf " --repo-url [REPOSITORY_URL]\tset luniebox repository url (default https://git.bstly.de/Lurkars/luniebox.git)\n"
	exit 0
}

while [ -n "$1" ]; do
	case "$1" in
	"-h" | "--help")
		help
		;;
	"-a" | "--automatic")
		AUTOMATIC=true
		;;
	"--no-updates")
		NO_UPDATES=true
		;;
	"--no-spotifydl")
		NO_SPOTIFYDL=true
		;;
	"--no-spotify")
		NO_SPOTIFY=true
		;;
	"--no-mpd")
		NO_MPD=true
		;;
	"--audio-device")
		AUDIO_DEVICE="$2"
		shift
		;;
	"--device-name")
		DEVICE_NAME="$2"
		shift
		;;
	"--mpu")
		NO_MPU=false
		;;
	"--repo-url")
		REPO_URL="$2"
		shift
		;;
	*)
		printf "\nargument '$1' not supported!\n\n"
		help
		;;
	esac
	shift
done

if [[ ${AUDIO_DEVICE} != "false" ]] && ! [[ ${AUDIO_DEVICES[*]} =~ "$AUDIO_DEVICE" ]]; then
	NO_AUDIO=true
	printf "Audio device '${AUDIO_DEVICE}' not supported, please set it up manually.\n"
fi

AUDIO_DEVICES+=("other")

start() {
	if [[ ${AUTOMATIC} == "false" ]]; then
		echo "##########################################
#  _             _      _                #
# | |_   _ _ __ (_) ___| |__   _____  __ #
# | | | | | '_ \| |/ _ \ '_ \ / _ \ \/ / #
# | | |_| | | | | |  __/ |_) | (_) >  <  #
# |_|\__,_|_| |_|_|\___|_.__/ \___/_/\_\ #
#                                        #
##########################################

Welcome to luniebox setup. This script will perfom some interactive 
steps to install and configure everything neccessary to convert this
device into a standalone spotify music box with RFID functionality.

If you want to run the script automatically, press n and restart script with -a option. 

Run the script with -h to get more information about possible options to be applied for setup process.
	"
		read -rp "Do you want to setup luniebox now? [Y/n] " response
		echo ""
		case "$response" in
		[nN][oO] | [nN])
			echo "Bye...."
			exit 0
			;;
		esac
	fi

	setup
}

setup() {
	cd /home/pi
	initialize
	update
	setup_device_name
	setup_software
	setup_rfid
	setup_audio
	setup_mpu
	finalize
}

initialize() {
	echo "Initizalize setup..."

	echo "Check for previous setup..."
	if [[ -f "${INSTALL_CONFIG_FILE}" ]]; then
		eval $(sed -r "/[^=]+=[^=]+/!d;s/\s+=\s/=/g" "${INSTALL_CONFIG_FILE}")
	fi

	if [[ -z ${SETUP_INITIALIZE+x} ]]; then
		echo "Install required packages..."
		sudo apt install -y git
		echo "Fetch luniebox repository..."
		git clone "${REPO_URL}" /home/pi/luniebox
		echo "Create config directory"
		mkdir -p /home/pi/luniebox/config
		echo "SETUP_INITIALIZE=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		echo "luniebox is already setup!"
	fi

	if [[ -z ${SETUP_REPO_URL+x} ]]; then
		echo "SETUP_REPO_URL=${REPO_URL}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		REPO_URL="${SETUP_REPO_URL}"
	fi
}

update() {
	if [[ -z ${SETUP_UPDATES+x} ]]; then
		if [[ ${NO_UPDATES} == "false" ]]; then
			if [[ ${AUTOMATIC} == "false" ]]; then
				read -rp "Do you want to update system now? [Y/n] (recommended) " response
				echo ""
				case "$response" in
				[nN][oO] | [nN])
					NO_UPDATES=true
					return 0
					;;
				esac
			fi

			echo "Update system"
			sudo apt update
			sudo apt upgrade -y
			echo "SETUP_UPDATES=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
		fi
	fi

	if [[ -z ${SETUP_NO_UPDATES+x} ]]; then
		echo "SETUP_NO_UPDATES=${NO_UPDATES}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		NO_UPDATES="${SETUP_NO_UPDATES}"
	fi
}

setup_software() {
	setup_app
	setup_spotify
	setup_mpd
	setup_zspotify
}

setup_app() {
	if [[ -z ${SETUP_APP+x} ]]; then
		echo "Install required packages..."
		sudo apt install -y python3-venv python3-pip
		cd /home/pi/luniebox/application
		echo "Setup python venv..."
		python -m venv venv
		source venv/bin/activate
		export CFLAGS=-fcommon
		echo "Install pip requirements..."
		pip install -r requirements.txt
		deactivate
		echo "Setup config and systemd services..."
		cp /home/pi/luniebox/contrib/config/luniebox.cfg /home/pi/luniebox/config/luniebox.cfg
		sudo cp /home/pi/luniebox/contrib/service/luniebox-app.service /etc/systemd/system/
		sudo cp /home/pi/luniebox/contrib/service/luniebox-daemon.service /etc/systemd/system/
		sudo systemctl daemon-reload
		sudo systemctl enable luniebox-app luniebox-daemon
		REBOOT=true
		echo "SETUP_APP=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	fi
}

setup_spotify() {
	if [[ -z ${SETUP_SPOTIFY+x} ]]; then
		if [[ ${NO_SPOTIFY} == "false" ]]; then
			if [[ ${AUTOMATIC} == "false" ]]; then
				read -rp "Do you want to install spotifyd for Spofity support? [Y/n] " response
				echo ""
				case "$response" in
				[nN][oO] | [nN])
					NO_SPOTIFY=true
					return 0
					;;
				esac
			fi

			mkdir -p /home/pi/luniebox/bin
			echo "Download spotifyd..."
			wget -c https://github.com/Spotifyd/spotifyd/releases/download/v0.3.3/spotifyd-linux-armv6-slim.tar.gz -O - | tar -xz -C /home/pi/luniebox/bin
			echo "Setup config and systemd services..."
			if [[ ${NO_AUDIO} == "true" ]]; then
				echo "WARNING: you may need to adjust the file '/home/pi/luniebox/config/spotifyd.cfg' manually to setup your audio device!"
				echo ""
			fi
			cp /home/pi/luniebox/contrib/config/spotifyd.cfg /home/pi/luniebox/config/spotifyd.cfg
			sed -i "s/^device_name.*=.*$/device_name = \"${DEVICE_NAME}\"/" /home/pi/luniebox/config/spotifyd.cfg
			sudo cp /home/pi/luniebox/contrib/service/spotifyd.service /etc/systemd/system/
			sudo systemctl daemon-reload
			sudo systemctl enable spotifyd
			REBOOT=true
			echo "SETUP_SPOTIFY=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
		fi
	fi

	if [[ -z ${SETUP_NO_SPOTIFY+x} ]]; then
		echo "SETUP_NO_SPOTIFY=${NO_SPOTIFY}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		NO_SPOTIFY="${SETUP_NO_SPOTIFY}"
	fi
}

setup_mpd() {
	if [[ -z ${SETUP_MPD+x} ]]; then
		if [[ ${NO_MPD} == "false" ]]; then
			if [[ ${AUTOMATIC} == "false" ]]; then
				read -rp "Do you want to install mpd (Music Player Daemon) for offline file support? [Y/n] " response
				echo ""
				case "$response" in
				[nN][oO] | [nN])
					NO_MPD=true
					return 0
					;;
				esac
			fi
			mkdir -p /home/pi/luniebox/library
			echo "Install required packages..."
			sudo apt install -y mpd
			echo "Setup config..."
			if [[ ${NO_AUDIO} == "true" ]]; then
				echo "WARNING: you may need to adjust the file '/etc/mpd.conf' manually to setup your audio device!"
				echo ""
			fi
			sudo cp /home/pi/luniebox/contrib/config/mpd.conf /etc/mpd.conf
			REBOOT=true
			echo "SETUP_MPD=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
		fi
	fi

	if [[ -z ${SETUP_NO_MPD+x} ]]; then
		echo "SETUP_NO_MPD=${NO_MPD}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		NO_MPD="${SETUP_NO_MPD}"
	fi
}

setup_zspotify() {
	if [[ -z ${SETUP_SPOTIFYDL+x} ]]; then
		if [[ ${NO_SPOTIFYDL} == "false" ]] && [[ ${NO_SPOTIFY} == "false" ]] && [[ ${NO_MPD} == "false" ]]; then
			if [[ ${AUTOMATIC} == "false" ]]; then
				read -rp "Do you want to install zspotify for downloading Spotify tracks for offline support? [Y/n] " response
				echo ""
				case "$response" in
				[nN][oO] | [nN])
					NO_MPD=true
					return 0
					;;
				esac
			fi

			echo "Fetch clspotify repository..."
			git clone https://github.com/agent255/clspotify.git /home/pi/clspotify
			cd /home/pi/clspotify
			echo "Setup python venv..."
			python -m venv venv
			source venv/bin/activate
			echo "Install pip requirements..."
			pip install -r requirements.txt
			deactivate
			echo "Setup config..."
			sed -i "s/^zspotify_path =.*$/zspotify_path = \/home\/pi\/clspotify\//" /home/pi/luniebox/config/luniebox.cfg
			REBOOT=true
			echo "SETUP_SPOTIFYDL=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
		fi
	fi

	if [[ -z ${SETUP_NO_SPOTIFY+x} ]]; then
		echo "SETUP_NO_SPOTIFYDL=${NO_SPOTIFYDL}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		NO_SPOTIFYDL="${SETUP_NO_SPOTIFYDL}"
	fi
}

setup_device_name() {
	if [[ -z ${SETUP_DEVICE_NAME+x} ]]; then
		if [[ ${AUTOMATIC} == "false" ]] && [[ ${DEVICE_NAME} == "false" ]]; then
			read -rp "Name for your Luniebox devices [default: luniebox]: " DEVICE_NAME
		fi

		if ! [[ $DEVICE_NAME ]] || [[ ${DEVICE_NAME} == "false" ]]; then
			DEVICE_NAME="luniebox"
		fi

		echo "Set device name to '${DEVICE_NAME}'"

		printf "${DEVICE_NAME}" | sudo tee /etc/hostname 1>/dev/null
		sudo sed -i "/^127.0.0.1/s/$/ ${DEVICE_NAME}/g" /etc/hosts
		REBOOT=true
		echo "SETUP_DEVICE_NAME=${DEVICE_NAME}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		DEVICE_NAME="${SETUP_DEVICE_NAME}"
	fi
}

setup_rfid() {
	if [[ -z ${SETUP_RFID+x} ]]; then
		echo "Enable SPI for RFID reader"
		sudo sed -i "/dtparam=spi=on/s/^#//g" /boot/config.txt
		REBOOT=true
		echo "SETUP_RFID=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	fi
}

setup_mpu() {
	if [[ -z ${SETUP_MPU+x} ]]; then
		if [[ ${AUTOMATIC} == "false" ]] && [[ ${NO_MPU} == "true" ]]; then
			read -rp "Do you want to setup I2C for MPU9250 9-axis sensor? [y/N] " response
			echo ""
			case "$response" in
			[yY][eE][sS] | [yY])
				NO_MPU=false
				;;
			*)
				return 0
				;;
			esac
		fi

		if [[ ${NO_MPU} == "false" ]]; then
			echo "Install I2C software, enable i2c bus 4, enable mpu"
			sudo apt install -y i2c-tools python3-smbus
			sudo sed -i "/dtparam=i2c_arm=on/s/^#//g" /boot/config.txt
			printf "\n# setup i2c bus 4 for mpu\ndtoverlay=i2c-gpio,bus=4,i2c_gpio_delay_us=1,i2c_gpio_sda=23,i2c_gpio_scl=24\n" | sudo tee -a /boot/config.txt 1>/dev/null
			sed -i "s/^mpu =.*$/mpu = True/" /home/pi/luniebox/config/luniebox.cfg
			REBOOT=true
			echo "SETUP_MPU=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
		fi
	fi

	if [[ -z ${SETUP_NO_MPU+x} ]]; then
		echo "SETUP_NO_MPU=${NO_MPU}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		NO_MPU="${SETUP_NO_MPU}"
	fi
}

setup_audio() {
	if [[ -z ${SETUP_AUDIO+x} ]]; then
		if [[ ${NO_AUDIO} == "false" ]]; then
			if [[ ${AUTOMATIC} == "false" ]]; then
				echo "Choose your audio hardware"
				select response in "${AUDIO_DEVICES[@]}"; do
					echo ""
					AUDIO_DEVICE="$response"
					break
				done
			fi

			case "$AUDIO_DEVICE" in
			"pimoroni")
				setup_pimoroni
				;;
			"adafruit")
				setup_adafruit
				;;
			*)
				NO_AUDIO=true
				echo "WARNING: please setup your audio device manually!"
				;;
			esac
		fi
	fi

	if [[ -z ${SETUP_AUDIO_DEVICE+x} ]]; then
		echo "SETUP_AUDIO_DEVICE=${AUDIO_DEVICE}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		AUDIO_DEVICE="${SETUP_AUDIO_DEVICE}"
	fi

	if [[ -z ${SETUP_NO_AUDIO+x} ]]; then
		echo "SETUP_NO_AUDIO=${NO_AUDIO}" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
	else
		NO_AUDIO="${SETUP_NO_AUDIO}"
	fi
}

setup_pimoroni() {
	echo "Setup Pimoroni Shim"
	sudo sed -i "/dtparam=audio=on/s/^/#/g" /boot/config.txt
	printf "\n# setup hifiberry for Pimoroni Shim\ndtoverlay=hifiberry-dac\ngpio=25=op,dh\n" | sudo tee -a /boot/config.txt 1>/dev/null
	REBOOT=true
	echo "SETUP_AUDIO=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
}

setup_adafruit() {
	echo "Setup Adafruit Speaker Bonnet"
	sudo sed -i "/dtparam=audio=on/s/^/#/g" /boot/config.txt
	printf "\n# setup hifiberry and i2s for Adafruit Speaker Bonnet\ndtoverlay=hifiberry-dac\ndtoverlay=i2s-mmap\n" | sudo tee -a /boot/config.txt 1>/dev/null
	cat /home/pi/luniebox/contrib/config/adafruit/asound.conf | sudo tee /etc/asound.conf 1>/dev/null
	cat /home/pi/luniebox/contrib/config/adafruit/.asoundrc | tee /home/pi/.asoundrc 1>/dev/null
	REBOOT=true
	echo "SETUP_AUDIO=true" | tee -a "${INSTALL_CONFIG_FILE}" 1>/dev/null
}

finalize() {
	if [[ ${REBOOT} == "true" ]]; then
		if [[ ${AUTOMATIC} == "false" ]]; then
			read -rp "Setup finished and reboot required. Do you want to automatically reboot your luniebox now? [Y/n] " response
			echo ""
			case "$response" in
			[nN][oO] | [nN])
				echo "Please reboot manually for luniebox working properly!"
				echo "Bye...."
				exit 0
				;;
			esac
		fi

		echo "Rebooting now...."
		sleep 1
		sudo reboot
		exit 0
	else
		echo "Bye...."
		exit 0
	fi
}

start
