#!/bin/sh

#############################################################################
# THIS MODULE IS USED TO INSTALL APPS FROM THE DATABASE OR FROM LOCAL SCRIPTS
#############################################################################

AMCLIPATH_ORIGIN="$AMCLIPATH"
BINDIR="${XDG_BIN_HOME:-$HOME/.local/bin}"
AMCATALOGUEICONS="${AMCATALOGUEICONS:-https://portable-linux-apps.github.io/icons}"

################################################################################
#				DOWNLOAD
################################################################################

_convert_to_appman_compatible_script() {
	_detect_appman_apps
	_appman
	if [ -d "$APPMAN_APPSPATH" ]; then
		sed -i "s# /usr/local/bin# $BINDIR#g" ./"$arg"
		sed -i "s# /usr/local/share/applications# $DATADIR/applications#g" ./"$arg"
		sed -i "s# /opt# $APPMAN_APPSPATH#g" ./"$arg"
		sed -i "s# https://api.github.com#$HeaderAuthWithGITPAT https://api.github.com#g" ./"$arg"
		cat <<-HEREDOC >> ./"$arg"

		# POST INSTALLATION PATCH FOR ALL LAUNCHERS
		sed -i "s#Exec=\$APP#Exec=$BINDIR/\$APP#g" $DATADIR/applications/*-AM.desktop
		sed -i "s#Exec=/usr/bin/#Exec=$BINDIR/#g" $DATADIR/applications/*-AM.desktop
		sed -i "s#Exec=/opt/#Exec=$HOME/$APPSDIR#g" $DATADIR/applications/*-AM.desktop
		sed -i "s#Icon=/opt/#Icon=$HOME/$APPSDIR#g" $DATADIR/applications/*-AM.desktop

		HEREDOC
		printf " Converting %s to an AppMan-compatible script.\r" "$arg" && sleep 0.25 &&
		printf "                                                                           \r"
	else
		echo ' 💀 ERROR: "--convert" requires a configuration file in ~/.config/appman'
	fi
}

_download() {
	if curl --output /dev/null --silent --head --fail "$APPSDB/$arg"  1>/dev/null; then
		cd "$SCRIPTDIR" || return 1
		if [ -f ./"$arg" ] || [ -d ./"$arg" ]; then
			echo "✖ \"$SCRIPTDIR/$arg\" already exists!" | _fit && return 1
		else
			wget -q "$APPSDB/$arg" && echo "◆ \"$arg\" installation script downloaded to \"$SCRIPTDIR\"! " | _fit
		fi
	else
		echo " 💀 ERROR: \"$arg\" is NOT a valid argument"
	fi
}

################################################################################
#				INSTALL
################################################################################

_check_if_optional_dependences_are_needed() {
	# Determine generic build utils
	app_deps="ar gcc glib-compile-schemas make tar unzip"
	script_content=$(cat ./"$arg")
	# Determine if this is an AppImage that can be compiled on-the-fly
	if grep -qi "^wget.*.sh.*chmod.*&&" ./"$arg"; then
		appimage_bulder_script=$(grep "^wget " ./"$arg" | tr '"' '\n' | grep -i "^http" | sed "s/\$APP/$arg/g")
		if curl --output /dev/null --silent --head --fail "$appimage_bulder_script" 1> /dev/null; then
			script_content=$(curl -Ls "$appimage_bulder_script")
			if echo "$script_content" | grep -ie "appimagetool\|pkg2appimage" 1>/dev/null; then
				if ! command -v convert >/dev/null 2>&1; then
					echo " 💀 ERROR: cannot create \"$arg\" without \"convert\" (from \"imagemagick\")"
					return 1
				fi
			fi
		else
			echo " 💀 ERROR: cannot create \"$arg\", the builder does not exists"
			return 1
		fi
	fi
	# Determine if this script installs a Firefox webapp
	if grep -q 'ffwa-' ./"$arg"; then
		ffbrowser=$(find ${PATH//:/ } -maxdepth 1 -name "firefox*" | sort | head -1)
		if [ -z "$ffbrowser" ]; then
			echo " 💀 ERROR: you cannot install \"$arg\" without installing \"firefox\""
			return 1
		else
			sed -i 's#firefox --class#'"$(echo "$ffbrowser" | xargs -L 1 basename)"' --class#g' ./"$arg"
		fi
	fi
	# Check missing dependency
	for name in $app_deps; do
		dependency_name="$name"
		[ "$name" = "ar" ] && dependency_name="binutils"
		if echo "$script_content" | grep -q "^$name" && ! command -v "$name" >/dev/null 2>&1; then
			echo " 💀 ERROR: cannot install \"$arg\" without \"$dependency_name\""
			return 1
		fi
	done
}

_check_if_script_installs_a_metapackage() {
	# Check if the installation script is a metapackage (example one of the 40+ kdegames scripts)
	[ ! -f "$AMDATADIR/$ARCH-apps" ] && _completion_lists
	for metapackage in $METAPACKAGES; do
		if grep "◆ $arg : " "$AMDATADIR/$ARCH-apps" | grep -q "\"$metapackage\""; then
			if [ -d "$APPSPATH"/"$metapackage"/tmp ]; then
				$SUDOCMD "$APPSPATH"/"$metapackage"/remove 2> /dev/null
			fi
			if [ -d "$APPSPATH"/"$metapackage" ] || command -v "$metapackage" >/dev/null 2>&1; then
				LASTDIR=$(echo "$metapackage" | tr '[:lower:]' '[:upper:]')
				echo " ◆ $APPNAME IS PART OF \"$LASTDIR\", ALREADY INSTALLED"
				return 1
			fi
		fi
	done
	metapkg_error_msg=" 💀 ERROR: \"$pure_arg\" also provides \"SCMD\", already in \$PATH"
	if [ "$pure_arg" = node ] && command -v npm >/dev/null 2>&1; then
		echo "$metapkg_error_msg" | tr '[:lower:]' '[:upper:]' | sed 's/SCMD/npm/g'
		return 1
	elif [ "$pure_arg" = platform-tools ] || [ "$pure_arg" = adb ] || [ "$pure_arg" = fastboot ]; then
		if command -v adb >/dev/null 2>&1; then
			echo "$metapkg_error_msg" | tr '[:lower:]' '[:upper:]' | sed 's/SCMD/adb/g'
			return 1
		elif command -v fastboot >/dev/null 2>&1; then
			echo "$metapkg_error_msg" | tr '[:lower:]' '[:upper:]' | sed 's/SCMD/fastboot/g'
			return 1
		fi
	fi
	
}

_check_if_spooky_flag_exists() {
	# Determine if an installation script is flagged as "spooky"
	if grep -i spooky ./"$arg" >/dev/null 2>&1; then
		printf "%b%b" " ${RED}WARNING:" " \"$arg\" does not have a transparent build process! \033[0m\n"
		printf "\n We can't be sure as to what is inside the application\n We highly recommend that you sandbox this application\n\n"
		read -r -p " Do you wish to continue? (N/y): " yn
		if ! echo "$yn" | grep -i '^y' >/dev/null 2>&1; then
			printf "\n INSTALLATION ABORTED! \n"
			return 1
		fi
	fi
}

_check_kind_of_installation_script() {
	# Check if you are installing an app or a library
	echo " ◆ $APPNAME: starting installation script"
	if grep -qi "^wget.*.sh.*chmod.*&&" ./"$arg"; then
		printf "\n This script will create an AppImage on the fly, please wait...\n"
	elif grep -q "/usr/local/lib" ./"$arg"; then
		[ "$arg" = libfuse2 ] && [ -f /usr/local/lib/libfuse.so.2 ] && echo " 💀 ERROR: \"$arg\" already exists in /usr/local/lib" && return 1
		printf "\n ⚠️ This script will install a system library in /usr/local/lib\n\n"
		read -r -p " Do you wish to continue? (N/y): " yn
		if ! echo "$yn" | grep -i '^y' >/dev/null 2>&1; then
			printf "\n INSTALLATION ABORTED! \n"
			return 1
		fi
	fi
}

_apply_patches() {
	# Patch "wget" (version 1.x) to have a progress bar and fix errors when applying patches
	if ! echo "$FLAGS" | grep -q -- "--debug" && wget --version | head -1 | grep -q ' 1.'; then
		sed -i "s#wget #wget -q --no-verbose --show-progress --progress=bar #g" ./"$arg"
	fi
	# Install the app so that it can rely on an icon theme (if available)
	if echo "$FLAGS" | grep -q -- '--icons'; then
		sed -i "s#Icon=/opt/\$APP/icons/#Icon=#g" ./"$arg"
	fi
	# If you use the --latest option, add the "latest" flag to scripts that point to a very common "release"
	if echo "$FLAGS" | grep -q -- '--force-latest'; then
		sed -i 's#/releases #/releases/latest #g' ./"$arg"
	fi
	# Patches /usr/local for $HOME equivalent for AppMan
	if [ "$AMCLI" = "appman" ]; then
		sed -i "s#/usr/local/bin#$BINDIR#g" ./"$arg"
		sed -i "s#/usr/local/share#$DATADIR#g" ./"$arg"
		sed -i "s#/opt/#$APPSPATH/#g" ./"$arg"
	else
		"$SUDOCMD" mkdir -p /usr/local/share/applications /usr/local/bin
	fi
	# Patch to apply to installation scripts
	sed -i "s# https://api.github.com#$HeaderAuthWithGITPAT https://api.github.com#g" ./"$arg"
	sed -i "s#DirIcon\$#DirIcon  2>/dev/null#g" ./"$arg"
	sed -i "s#DirIcon ./icons/\"\$APP\" 1#DirIcon ./icons/\"\$APP\" 2#g" ./"$arg"
	echo ""
	# Use GNU implementation of "sed"
	if [ "$NO_SED_I" = true ]; then
		if command -v gsed >/dev/null 2>&1; then
			sed -i "s/sed -i/gsed -i/g" ./"$arg"
		else
			sed -i "s/sed -i/sed -i'' -e/g" ./"$arg"
		fi
	fi
}

_torsocks_error_message() {
	echo "💀 Cannot install \"$arg\", $TORSOCKS_MESSAGE"
	printf "\nInstall \"torsocks\" from your system package manager and retry! \n"
}

_post_installation_processes() {
	LASTDIR=$(ls -td "$APPSPATH"/* | head -1 | sed 's:.*/::')
	LASTDIRPATH="${APPSPATH}/${LASTDIR}"
	# Put permission check in remove script and change ownership of directory
	if [ "$AMCLI" = am ]; then
		$SUDOCMD sed -i "1 a [ \"\$(id -u)\" -ne 0 ] && echo "Permission denied" && exit 1" \
			"${LASTDIRPATH}"/remove 2>/dev/null
		$SUDOCMD chown -R "$USER" "${LASTDIRPATH}" 2>/dev/null
	fi
	# Check for AM-updater script sothat CLI can manage updates
	[ -f "${LASTDIRPATH}"/AM-updater ] && mkdir "${LASTDIRPATH}"/.am-installer 2>/dev/null \
		&& curl -Ls "$APPSDB"/"$arg" > "${LASTDIRPATH}"/.am-installer/"$arg"
	find "${LASTDIRPATH}"/icons/* -xtype l -delete 2>/dev/null # Removes broken links
	# If you have a broken or missing icon in your "icons" directory, download one from the catalog
	[ -z "$(ls -A "${LASTDIRPATH}"/icons 2>/dev/null)" ] \
		&& wget -q "$AMCATALOGUEICONS"/"$arg".png -O "${LASTDIRPATH}"/icons/"$arg" 2>/dev/null
	# Patch .desktop to change paths if the app is installed locally
	if [ "$AMCLI" = "appman" ]; then
		for a in $DATADIR/applications/*-AM.desktop; do
			sed -i "s#Exec=$arg#Exec=$BINDIR/$arg#g" "$a" 2>/dev/null
			sed -i "s#Exec=/usr/bin/#Exec=$BINDIR/#g" "$a" 2>/dev/null
			sed -i "s#Exec=/opt/#Exec=$BINDIR/#g" "$a" 2>/dev/null
		done
	fi
	# Export all icons for hicolor theme usage
	if echo "$FLAGS" | grep -q -- '--icons'; then
		_icon_theme_export_to_datadir 2>/dev/null
	fi
}

_ending_the_installation() {
	LASTDIR=$(ls -td "$APPSPATH"/* | head -1 | sed 's:.*/::')
	if [ -f "${LASTDIRPATH}"/remove ]; then
		if test -d "${LASTDIRPATH}"/tmp; then
			echo " 💀 ERROR DURING INSTALLATION, REMOVED $APPNAME!"
			$SUDOCMD "$APPSPATH/$LASTDIR/remove" 1>/dev/null
		elif test -f "$APPSPATH/$LASTDIR/version" && [ -z "$(cat "$APPSPATH/$LASTDIR/version")" ]; then
			echo " 💀 ERROR DURING INSTALLATION, REMOVED $APPNAME!"
			$SUDOCMD "$APPSPATH/$LASTDIR/remove" 1> /dev/null
		else
			APPSIZE=$(du -sm "${LASTDIRPATH}" | awk '{print $1}' )
			LASTDIRNAME=$(echo "\"$LASTDIR\"" | tr '[:lower:]' '[:upper:]')
			printf "%b%b%s\n" " ${Green}" "$LASTDIRNAME INSTALLED\033[0m" " ($APPSIZE MB OF DISK SPACE)"
			$SUDOCMD rm "$AMCACHEDIR"/"$arg"
			_check_version
			app_version=$(grep -w " ◆ $LASTDIR	|" 0<"$AMCACHEDIR"/version-args | sed 's:.*|	::')
			echo " ◆ $LASTDIR $app_version" >> "$AMCACHEDIR"/installed
		fi
	else
		echo " INSTALLATION ABORTED!"
	fi
}

_install_arg() {
	# This function is needed to parse the installation script and then execute it
	APPNAME=$(echo "\"$pure_arg\"" | tr '[:lower:]' '[:upper:]')
	chmod a+x ./"$arg"
	_check_if_optional_dependences_are_needed || return 1
	_check_if_script_installs_a_metapackage || return 1
	_check_if_spooky_flag_exists || return 1
	_check_kind_of_installation_script || return 1
	_apply_patches
	# Determine if Torsocks is needed
	if command -v torsocks 1>/dev/null; then
		TORSOCKS="1"
	fi
	if grep -q "https://repology.org" ./"$arg"; then
		REPOLOGY_API_ALLOWED=$(curl -Ls https://repology.org/)
		TORSOCKS_MESSAGE="you have no access to https://repology.org, needed to check the version of this program."
		if grep -q "https://repology.org" ./"$arg" && [ -z "$REPOLOGY_API_ALLOWED" ] && [ -n "$TORSOCKS" ]; then
			sed -i "s/version=\$(wget/version=\$(torsocks wget/g" ./"$arg"
		fi
		[ -z "$REPOLOGY_API_ALLOWED" ] && [ -z "$TORSOCKS" ] && _torsocks_error_message | fold -sw 72 | sed 's/^/   /g; s/   ✖/✖/g' && return 0
	elif grep -q "api.github.com" ./"$arg"; then
		GH_API_ALLOWED=$(curl -Ls $HeaderAuthWithGITPAT https://api.github.com/repos/ivan-hc/AM/releases/latest | sed 's/[()",{} ]/\n/g' | grep "^ivan-hc" | head -1)
		TORSOCKS_MESSAGE="you have reached GitHub API limit."
		[ -z "$GH_API_ALLOWED" ] && [ -z "$TORSOCKS" ] && _torsocks_error_message | fold -sw 72 | sed 's/^/   /g; s/   ✖/✖/g' && return 0
	fi
	# Install script
	if grep -q "api.github.com" ./"$arg" && [ -z "$GH_API_ALLOWED" ] && [ -n "$TORSOCKS" ]; then
		$SUDOCMD torsocks ./"$arg"
	else
		$SUDOCMD ./"$arg"
	fi
	echo ""
	_post_installation_processes
	_ending_the_installation
}

################################################################################
#			INSTALLATION CASES
################################################################################

_determine_pure_arg_name() {
	pure_arg=$(echo "$arg" | sed 's/\.toolpack//g; s/\.dwfs.appbundle$//g; s/\.appbundle$//g; s/\.nixappimage//g')
	pure_arg=$(echo "$pure_arg" | sed 's/\.appimage//g; s/\-appimage$//g' | sed 's:.*/::')
	echo "$arg" | grep -q -- "-appimage$" && curl -Ls "$APPSDB"/"$arg" | grep -q "APP=.*-appimage$" && pure_arg="$arg"
}

_install_appimage() {
	# This function is ment to select and install only AppImages
	rm -f "$AMCACHEDIR"/install-args
	_sync_appimages_list
	for arg in $entries; do
		if grep -q "^◆ $arg : " "$AMDATADIR/$ARCH-appimages"; then
			echo "$arg" >> "$AMCACHEDIR"/install-args
		else
			arg="$arg-appimage"
			if ! grep -q "^◆ $arg : " "$AMDATADIR/$ARCH-appimages"; then
				echo "$DIVIDING_LINE"
				echo " ✖ \"$(echo "$arg" | sed 's/-appimage//g')\" is not an Appimage"
				echo "$DIVIDING_LINE"
			else
				echo "$arg" >> "$AMCACHEDIR"/install-args
			fi
		fi
	done
	entries=$(cat "$AMCACHEDIR"/install-args 2>/dev/null)
}

_install_local_script() {
	# This function is for local installation scripts
	path2arg="$arg"
	arg=$(echo "$path2arg" | sed 's:.*/::')
	mkdir -p "$AMCACHEDIR"/tmp && rm -f "$AMCACHEDIR"/tmp/* || return 1
	cp "$path2arg" "$AMCACHEDIR"/tmp/"$arg" && cd "$AMCACHEDIR" && mv ./tmp/"$arg" ./"$arg" && rmdir ./tmp || return 1
	if ! test -d "$APPSPATH"/"$arg"; then
		_install_arg
	fi
}

_install_normally() {
	# This is for scripts hosted on the official online database
	mkdir -p "$AMCACHEDIR"/tmp && rm -f "$AMCACHEDIR"/tmp/* || return 1
	curl -Ls "$APPSDB"/"$arg" > "$AMCACHEDIR"/tmp/"$arg" || return 1
	cd "$AMCACHEDIR" && mv ./tmp/"$arg" ./"$arg" && rmdir ./tmp || return 1
	_install_arg
}

################################################################################
#			THIRD PARTY DATABASES
################################################################################

_3rd_party_check() {
	echo "$@" | grep -q -- "--toolpack" || echo "$arg" | grep -q ".toolpack$" || echo "$arg" | grep -q ".appbundle$"
}

_3rd_party_apps_handler() {
	# This function is needed to handle programs from third-party supported databases
	mkdir -p "$CACHEDIR/extra"
	if echo "$arg" | grep -q "appbundle$"; then
		[ -n "$appbundle_readme" ] && third_party_readme="$appbundle_readme"
	else
		[ -n "$toolpack_readme" ] && third_party_readme="$toolpack_readme"
	fi
	awk_version="curl -Ls $third_party_readme | grep -i \"^| $arg \" | tr '|' '\\\n' | cut -c 2- | grep . | awk -F: \"NR==$awk_ver\""
	third_party_url="curl -Ls $third_party_readme | grep -i \"^| $arg \" | tr '|' '\\\n' | cut -c 2- | grep . | awk -F: \"NR==$awk_dl\""
	if echo "$arg" | grep -q "appbundle$"; then
		curl -Ls "$AMREPO"/templates/AM-SAMPLE-AppBundle > "$CACHEDIR/extra/$arg.toolpack" || exit 1
		sed -i "s#APP=SAMPLE#APP=$arg#g; s#FUNCTION#$awk_version#g; s#wget \"\$version\"#wget \$($third_party_url)#g" "$CACHEDIR/extra/$arg.toolpack"
		sed -i 's/\.dwfs.appbundle$//g; s/\.appbundle$//g' "$CACHEDIR/extra/$arg.toolpack"
	elif echo "$arg" | grep -q "nixappimage$"; then
		curl -Ls "$AMREPO"/templates/AM-SAMPLE-AppImage > "$CACHEDIR/extra/$arg.toolpack" || exit 1
		sed -i "s#APP=SAMPLE#APP=$arg#g; s#FUNCTION#$awk_version#g; s#wget \"\$version\"#wget \$($third_party_url)#g" "$CACHEDIR/extra/$arg.toolpack"
		sed -i 's/\.nixappimage$//g' "$CACHEDIR/extra/$arg.toolpack"
	else
		curl -Ls "$AMREPO"/templates/AM-SAMPLE-Archive > "$CACHEDIR/extra/$arg.toolpack" || exit 1
		sed -i "s#APP=SAMPLE#APP=$arg#g; s#FUNCTION#$awk_version#g; s#wget \"\$version\"#wget \$($third_party_url)#g" "$CACHEDIR/extra/$arg.toolpack"
		sed -e '/\[ -e/ s/^#*/#/' -i "$CACHEDIR/extra/$arg.toolpack" 2>/dev/null
	fi
	chmod a+x "$CACHEDIR/extra/$arg.toolpack"
	arg="$CACHEDIR/extra/$arg.toolpack"
}

_install_3rd_party_app() {
	arg=$(echo "$arg" | sed 's/\.toolpack//g; s/\.appimage//g')
	if curl -Ls "$appbundle_readme" 2>/dev/null | grep -q "^| $arg " || curl -Ls "$toolpack_readme" 2>/dev/null | grep -q "^| $arg "; then
		_3rd_party_apps_handler
		_install_local_script
	else
		echo " 💀 ERROR, \"$arg\" does NOT exist in 3rd-party databases:"
		printf "\nTry without the \"--toolpack\" flag or run \"%b$AMCLIPATH_ORIGIN -l --all\033[0m\" to check all lists.\n" "${Gold}" | fold -sw 72 | sed 's/^/ /g'
	fi
}

################################################################################
#				USAGE
################################################################################

case "$1" in
	'-d'|'download')
		case $2 in
		'--convert')
			[ -z "$3" ] && echo " USAGE: $AMCLI $1 $2 [ARGUMENT]" && exit 1
			;;
		'')
			echo " USAGE: $AMCLI $1 [ARGUMENT]"
			echo " USAGE: $AMCLI $1 --convert [ARGUMENT]"
			exit 1
			;;
		esac
		if [ "$2" = "--convert" ]; then
			entries="$(echo "$@" | cut -f3- -d ' ')"
			for arg in $entries; do
				_download
				_convert_to_appman_compatible_script
			done
		else
			entries="$(echo "$@" | cut -f2- -d ' ')"
			for arg in $entries; do
				_download
			done
		fi
		;;

	'install'|'-i'|'-ias'|\
	'install-appimage'|'-ia')
		[ "$AMCLI" = "am" ] && echo "$@" | grep -q -- "--user" && _appman

		case $2 in
		'')
			echo " USAGE: $AMCLI $1 [ARGUMENT]"
			echo " USAGE: $AMCLI $1 --debug [ARGUMENT]"
			echo " USAGE: $AMCLI $1 --force-latest [ARGUMENT]"
			echo " USAGE: $AMCLI $1 --icons [ARGUMENT]"
			echo " USAGE: $AMCLI $1 --sandbox [ARGUMENT]"
			[ "$AMCLI" = "am" ] && echo " USAGE: $AMCLI $1 --user [ARGUMENT]"
			exit 1
			;;
		esac

		[ "$AMCLI" = "am" ] && { $SUDOCMD printf "\r" || exit 1; }

		echo "============================================================================"
		printf "\n                  %bSTART OF ALL INSTALLATION PROCESSES\033[0m\n\n" "${LightBlue}"
		echo "============================================================================"
		_clean_amcachedir 2>/dev/null

		entries="$(echo "$@" | cut -f2- -d ' ' | tr ' ' '\n' | grep -v -- "--")"
		FLAGS=$(echo "$@" | tr ' ' '\n' | grep -- "--" | tr '\n ' ' ')
		METAPACKAGES="kdegames kdeutils node platform-tools"

		if [ "$1" = "-ia" ] || [ "$1" = "install-appimage" ]; then _install_appimage; fi
		if [ "$1" = "-ias" ]; then FLAGS=$(printf "%b\n--sandbox\n" "$FLAGS"); _install_appimage; fi

		for arg in $entries; do
			echo ""
			cd "$REALDIR" || return 1
			# If the "tmp" directory is not removed, the installation failed, so remove the app
			[ -d "$APPSPATH"/"$arg"/tmp ] && $SUDOCMD "$APPSPATH"/"$arg"/remove 2> /dev/null

			# Check if the app wil be installed with the same name as the argument
			_determine_pure_arg_name

			# Test if a symlink is broken
			[ -n "$BINDIR" ] && find "$BINDIR" -xtype l -name "$pure_arg" -delete 2>/dev/null
			# Various cases that may occur during installation
			if test -f "$APPSPATH"/"$pure_arg"/remove || test -f "$APPSPATH"/"$pure_arg"/remove.old; then
				echo " ◆ \"$pure_arg\" is already installed!" | tr '[:lower:]' '[:upper:]'
			elif [ -n "$(PATH=/usr/local/bin command -v "$pure_arg" 2>/dev/null)" ] && [ "$AMCLI" = am ]; then
				echo " 💀 ERROR: \"$pure_arg\" command already exists!"
			elif echo "$arg" | grep -q "/"; then
				if test -f "$arg" 2> /dev/null; then
					_install_local_script
				else
					echo " 💀 ERROR: the file \"$arg\" does NOT exist"
				fi
			elif _3rd_party_check "$@"; then
				_install_3rd_party_app
			elif curl --output /dev/null --silent --head --fail "$APPSDB"/"$arg" 1>/dev/null; then
				_install_normally
			else
				echo "💀 ERROR: \"$arg\" does NOT exist in the \"AM\" database, $(printf "please check the list, run the \"%b$AMCLIPATH_ORIGIN -l\033[0m\" command.\n\n" "${Gold}")" | fold -sw 72 | sed 's/^/ /g'
			fi
			# Sandbox argument
			if echo "$FLAGS" | grep -q -- "--sandbox" && [ "$LASTDIR" != aisap ]; then
				if [ -f "$APPSPATH/$LASTDIR/$LASTDIR" ]; then
					if ! command -v aisap >/dev/null 2>&1; then
						mv "$AMCACHEDIR"/installed "$CACHEDIR"/installed.backup.am 2>/dev/null
						"$AMCLIPATH_ORIGIN" --sandbox "$LASTDIR"
						sort "$AMCACHEDIR"/installed >> "$CACHEDIR"/installed.backup.am 2>/dev/null
						mv "$CACHEDIR"/installed.backup.am "$AMCACHEDIR"/installed 2>/dev/null
					else
						echo ""
						"$AMCLIPATH_ORIGIN" --sandbox "$LASTDIR"
					fi
				else
					printf "\n ERROR: \"%b\" is NOT an AppImage\n" "$LASTDIR"
				fi
			fi
			echo "____________________________________________________________________________"
		done
		echo "============================================================================"
		printf "\n                  %bEND OF ALL INSTALLATION PROCESSES\n\033[0m" "${LightBlue}"
		[ -f "$AMCACHEDIR"/installed ] && printf "\n             The following new programs have been installed:\n\n" \
		&& sort "$AMCACHEDIR"/installed | grep -w -v "◆ am"
		printf "\n============================================================================\n"
		exit 0
		;;

	'-e'|'extra')
		if [ -z "$2" ] || [ -z "$3" ]; then
			echo " USAGE: $AMCLI $1 user/project [ARGUMENT]"
			echo " USAGE: $AMCLI $1 user/project [ARGUMENT] [KEYWORD]"
			[ "$AMCLI" = "am" ] && echo " USAGE: $AMCLI $1 --user user/project [ARGUMENT]"
			[ "$AMCLI" = "am" ] && echo " USAGE: $AMCLI $1 --user user/project [ARGUMENT] [KEYWORD]"
			exit 1
		fi
		case $2 in
		'--user')
			USER_PROJECT=$(echo "$3" | sed 's#https://github.com/##g' | cut -f1,2 -d'/')
			EXTERNAL_APP_NAME="$4"
			APP_KEYWORD="$5"
			;;
		*)
			USER_PROJECT=$(echo "$2" | sed 's#https://github.com/##g' | cut -f1,2 -d'/')
			EXTERNAL_APP_NAME="$3"
			APP_KEYWORD="$4"
			;;
		esac
		mkdir -p "$CACHEDIR/extra"
		curl -Ls "$AMREPO"/templates/AM-SAMPLE-AppImage > "$CACHEDIR/extra/$EXTERNAL_APP_NAME" || exit 1
		sed -i "s#APP=SAMPLE#APP=$EXTERNAL_APP_NAME#g" "$CACHEDIR/extra/$EXTERNAL_APP_NAME"
		API_GITHUB_REPO="https://api.github.com/repos/$USER_PROJECT/releases"
		sed -i "s#REPLACETHIS#$USER_PROJECT#g" "$CACHEDIR/extra/$EXTERNAL_APP_NAME"
		q="'"
		if [ "$ARCH" = "x86_64" ]; then
			FILTER=' | grep -vi "i386\\|i686\\|i586\\|i486\\|aarch64\\|arm64\\|armv7l"'
		elif [ "$ARCH" = "i686" ]; then
			FILTER=' | grep -ie "i386\\|i686\\|i586\\|i486" '
		elif [ "$ARCH" = "aarch64" ]; then
			FILTER=' | grep -ie "aarch64\\|arm64" '
		fi
		FUNCTION='curl -Ls '"$API_GITHUB_REPO"' | sed '"$q"'s/[()",{} ]/\\n/g'"$q"' | grep -oi "https.*mage$"'"$FILTER"' | head -1'
		sed -i "s#FUNCTION)#$FUNCTION)#g" "$CACHEDIR/extra/$EXTERNAL_APP_NAME"
		[ -n "$APP_KEYWORD" ] && sed -i "s# head -1# grep -i \"$APP_KEYWORD\" | head -1#g" "$CACHEDIR/extra/$EXTERNAL_APP_NAME"
		chmod a+x "$CACHEDIR/extra/$EXTERNAL_APP_NAME"
		[ "$AMCLI" = "am" ] && [ "$2" = "--user" ] && "$AMCLIPATH_ORIGIN" -i --user "$CACHEDIR/extra/$EXTERNAL_APP_NAME" \
		|| "$AMCLIPATH_ORIGIN" -i "$CACHEDIR/extra/$EXTERNAL_APP_NAME"
		exit 1
		;;
esac
