#!/bin/sh

# Colors
RED='\033[0;31m'; LightBlue='\033[1;34m'; Green='\033[0;32m'

# For developers
AM_BRANCH="main"

# Check dependencies for this script
_check_dependency() {
	AMDEPENDENCES="chmod chown curl grep wget"
	for dependency in $AMDEPENDENCES; do
		if ! command -v "$dependency" >/dev/null 2>&1; then
			printf "\n %b💀 ERROR! MISSING ESSENTIAL COMMAND \033[0m: %b\n\n Install the above and try again! \n\n" "${RED}" "$dependency"
			exit 1
		fi
	done
}

_check_dependency

if [ -z "${SUDO_USER:-$DOAS_USER}" ]; then
	echo 'Please use sudo or doas'
	exit 1
fi

# INSTALL "AM"
_prepare_am_directory() {
	# CREATE AND ENTER THE MAIN DIRECTORY FOR "AM"
	mkdir -p /opt/am/modules /usr/local/bin && cd /opt/am || exit 1

	# CREATE THE SCRIPT NEEDED TO UNINSTALL "AM"
	printf '#!/bin/sh\n\nset -e\n' > /opt/am/remove
	printf '\n%s\n' 'if [ "$(id -u)" -ne 0 ]; then echo "Permission denied"; exit 1; fi' >> /opt/am/remove
	printf '%s\n' 'rm -f /usr/local/bin/am' >> /opt/am/remove
	printf '%s\n' 'rm -R -f /opt/am' >> /opt/am/remove
	chmod a+x /opt/am/remove || exit 1

	# DOWNLOAD AND LINK THE MAIN SCRIPT
	wget -q "https://raw.githubusercontent.com/ivan-hc/AM/$AM_BRANCH/APP-MANAGER"
	chmod a+x /opt/am/APP-MANAGER
	ln -s /opt/am/APP-MANAGER /usr/local/bin/am 2> /dev/null || printf "${RED}WARNING: Couldn't link am to \"/usr/local/bin/am\"!\033[0m\n"
}

_download_am_modules() {
	# DOWNLOAD MODULES
	cd /opt/am/modules || exit
	MODULES=$(curl -Ls "https://raw.githubusercontent.com/ivan-hc/AM/$AM_BRANCH/APP-MANAGER" | tr '"' '\n' | grep "[a-z]\.am$")
	for module_name in $MODULES; do
		if [ ! -f ./"$module_name" ]; then
			echo " ◆ Downloading $module_name..."
			wget -q "https://raw.githubusercontent.com/ivan-hc/AM/$AM_BRANCH/modules/$module_name"
			chmod a+x ./"$module_name"
		fi
	done
	cd ..

	# ENABLE NON-ROOT PERMISSIONS TO THE MAIN DIRECTORY FOR THE CURRENT USER
	chown -R "${SUDO_USER:-$DOAS_USER}" /opt/am 2>/dev/null
}

echo '--------------------------------------------------------------------------'
printf " ${Green}Installing \"AM\" in /opt/am\033[0m\n"
_prepare_am_directory
echo '--------------------------------------------------------------------------'
printf " ${Green}Installing modules\033[0m\n"
_download_am_modules
echo '--------------------------------------------------------------------------'
printf " ${Green}\"AM\" has been successfully installed!\033[0m\n"
printf " Please, run \"${LightBlue}am -h\033[0m\" to see the list of the options.\n"
echo '--------------------------------------------------------------------------'
