#!/bin/bash
#
# wf-installer
#
# Copyright (C) 2026 Adrian "asie" Siekierka
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

set -e
set -u
set -o pipefail

# Configuration

VERSION=20260603
BOOTSTRAP_DOWNLOAD_PATH="https://wonderful.asie.pl/bootstrap"
INSTALL_PATH="/opt/wonderful"

main() {

# Helper functions

find_one_of_tools() {
	for TOOL in "$@"; do
		if command -v "$TOOL" >/dev/null; then
			echo "$TOOL"
			return 0
		fi
	done
}

add_code_to_profile() {
	TMPFILE="$(mktemp)"

	if [[ -f "$1" ]]; then
		if [[ ! -w "$1" ]]; then
			echo "[!] $1 is not writable, skipping..."
			return 0
		fi
		sed '/# Begin Wonderful Toolchain wf-installer code/,/# End Wonderful Toolchain wf-installer code/d' "$1" > "$TMPFILE"
	fi
	echo "# Begin Wonderful Toolchain wf-installer code" >> "$TMPFILE"
	echo "$2" >> "$TMPFILE"
	echo "# End Wonderful Toolchain wf-installer code" >> "$TMPFILE"

	mv "$TMPFILE" "$1" || echo "[!] $1 is not writable, skipping..."
}

# Script

echo ""
echo "  :   '. .'."
echo " :     : : :  Wonderful Toolchain"
echo " :  .  :':'   installer v$VERSION"
echo " '..'..' :'"
echo ""

TARGET="$(uname -s)/$(uname -m)"
DOWNLOAD_PATH=""
SKIP_PATH_CHOICE=""
SKIP_INSTALL=""

case "$TARGET" in
	Linux/x86_64)
		DOWNLOAD_PATH="$BOOTSTRAP_DOWNLOAD_PATH/wf-bootstrap-x86_64.tar.gz"
		;;
	Linux/aarch64)
		DOWNLOAD_PATH="$BOOTSTRAP_DOWNLOAD_PATH/wf-bootstrap-aarch64.tar.gz"
		;;
	*)
		echo -e "[!] Unsupported operating system/architecture pair ($TARGET)."
		exit 1
		;;
esac

echo "<~> Verifying installation environment..."

VERIFIED=1

# Alpine Linux does not ship /bin/bash by default.
# However, Alpine Linux images under lima ship a fake script that redirects /bin/bash to /bin/ash.
if [[ -z "$BASH_VERSION" ]]; then
	echo -e "[!] bash is not installed. Please install bash before continuing."
	VERIFIED=0
fi

for TOOL in chown ls make mkdir mktemp sed tar; do
	if ! command -v "$TOOL" >/dev/null; then
		echo -e "[!] $TOOL is not installed. Please install $TOOL before continuing."
		VERIFIED=0
	fi
done

DOWNLOAD_TOOL="$(find_one_of_tools curl wget)"
if [[ -z "$DOWNLOAD_TOOL" ]]; then
	echo -e "[!] No supported download tool found. Please install curl or wget before continuing."
	VERIFIED=0
fi

if [[ "$VERIFIED" = 0 ]]; then
	exit 1
fi

if [[ -z "$SKIP_PATH_CHOICE" ]]; then
	echo ""
	echo "Please choose the installation path:"
	echo "1) $INSTALL_PATH [default, recommended]"
	echo "2) $HOME/.wonderful [experimental]"
	echo "3) User-specified path [experimental]"

	while true; do
		read -p "Enter choice [1-3]: " choice </dev/tty

		case "$choice" in
			""|1)
				break
				;;
			2)
				INSTALL_PATH="$HOME/.wonderful"
				break
				;;
			3)
				read -p "Enter path: " CUSTOM_INSTALL_PATH </dev/tty
				if [[ "$CUSTOM_INSTALL_PATH" = "/" ]]; then
					echo "[!] Installing to $CUSTOM_INSTALL_PATH is not a good idea."
				elif [[ -n "$CUSTOM_INSTALL_PATH" ]]; then
					INSTALL_PATH="$CUSTOM_INSTALL_PATH"
					break
				fi
				;;
		esac
	done
fi

if [[ -n "$(ls -A "$INSTALL_PATH" 2>/dev/null)" ]]; then
	echo "[!] The installation directory is not empty."
	read -p "Do you wish to continue? [y/N]: " choice </dev/tty
	case "$choice" in
		Y*|y*)
			;;
		*)
			read -p "Do you wish to update your environment configuration? [y/N]: " choice </dev/tty
			case "$choice" in
				Y*|y*)
					SKIP_INSTALL=1
					;;
				*)
					exit 1
					;;
			esac
			;;
	esac
fi

if [[ -z "$SKIP_INSTALL" ]]; then
	if [[ ! -w "$INSTALL_PATH" ]]; then
		INSTALL_PATH_PARENT="$(dirname "$INSTALL_PATH")"
		if [[ -w "$INSTALL_PATH_PARENT" ]]; then
			mkdir -p "$INSTALL_PATH"
		else
			SUDO_TOOL="$(find_one_of_tools sudo run0 doas)"
			if [[ -z "$SUDO_TOOL" ]]; then
				echo -e "[!] No privilege escalation tool found. Could not create installation directory. Please install sudo (recommended), run0 or doas."
				exit 1
			fi
			echo -e "[!] Privilege escalation required to access $INSTALL_PATH..."
			"$SUDO_TOOL" sh -c "mkdir -p "$INSTALL_PATH" && chown -R "$USER" "$INSTALL_PATH""
		fi
	fi

	echo ""
	echo "<~> Downloading bootstrap..."

	BOOTSTRAP_PATH="$(mktemp)"
	trap "rm "$BOOTSTRAP_PATH"" EXIT
	case "$DOWNLOAD_TOOL" in
		curl)
			curl -o "$BOOTSTRAP_PATH" "$DOWNLOAD_PATH"
			;;
		wget)
			wget -O "$BOOTSTRAP_PATH" "$DOWNLOAD_PATH"
			;;
	esac

	echo ""
	echo "<~> Extracting bootstrap..."

	tar -xzf "$BOOTSTRAP_PATH" -C "$INSTALL_PATH"/

	if [[ ! -f "$INSTALL_PATH/bin/wf-pacman" ]]; then
		echo "[!] Bootstrap extraction failed! (corrupt file?)"
		exit 1
	fi

	echo "<~> Updating toolchain base..."

	"$INSTALL_PATH/bin/wf-pacman" -Syu --noconfirm wf-tools
fi

echo ""
echo "Choose the desired environment configuration:"
echo "1) Export WONDERFUL_TOOLCHAIN, add wf-tools to PATH. [default, recommended]"
echo "2) Export WONDERFUL_TOOLCHAIN, add wf-tools and all toolchains to PATH."
echo "3) Export WONDERFUL_TOOLCHAIN only."
echo "4) Do not make changes to my .profile."

PROFILE_CODE=""
PROFILE_CODE_SIMPLE=""
PROFILE_HAS_WF_ENV=0
PROFILE_CODE_EXPORT="export WONDERFUL_TOOLCHAIN=\"$INSTALL_PATH\""
PROFILE_CODE_ALIAS="alias wf-env='source $INSTALL_PATH/bin/wf-env'"
while true; do
	read -p "Enter choice [1-4]: " choice </dev/tty

	case "$choice" in
		""|1)
			PROFILE_HAS_WF_ENV=1
			PROFILE_CODE="$(echo -e "$PROFILE_CODE_EXPORT\n$PROFILE_CODE_ALIAS\nwf-env")"
			PROFILE_CODE_SIMPLE="$(echo -e "$PROFILE_CODE_EXPORT\nexport PATH=\"$INSTALL_PATH/bin:\$PATH\"")"
			break
			;;
		2)
			PROFILE_HAS_WF_ENV=1
			PROFILE_CODE="$(echo -e "$PROFILE_CODE_EXPORT\n$PROFILE_CODE_ALIAS\nwf-env -a")"
			PROFILE_CODE_SIMPLE="$(echo -e "$PROFILE_CODE_EXPORT\nexport PATH=\"$INSTALL_PATH/bin:\$PATH\"")"
			break
			;;
		3)
			PROFILE_CODE="$(echo -e "$PROFILE_CODE_EXPORT\n$PROFILE_CODE_ALIAS")"
			PROFILE_CODE_SIMPLE="$(echo -e "$PROFILE_CODE_EXPORT")"
			break
			;;
		4)
			break
			;;
	esac
done
if [[ -n "$PROFILE_CODE" ]]; then
	echo ""
	echo "<~> Applying changes..."
	add_code_to_profile ~/.profile "$PROFILE_CODE_SIMPLE"
	add_code_to_profile ~/.bash_profile "$PROFILE_CODE"
	if [[ -f ~/.zshrc ]]; then
		add_code_to_profile ~/.zprofile "$PROFILE_CODE"
	fi
fi

if [[ -z "$SKIP_INSTALL" ]]; then
	echo ""
	echo "^_^ Installation complete!"
fi
echo ""
if [[ -n "$PROFILE_CODE" ]]; then
	if [[ "$PROFILE_HAS_WF_ENV" = "1" ]]; then
		echo "To use Wonderful Toolchain, log out and log back in."
	else
		echo "To use Wonderful Toolchain, log out and log back in, then run wf-env in your shell."
	fi
else
	echo "To use Wonderful Toolchain, run the following commands:"
	echo ""
	echo "$ export WONDERFUL_TOOLCHAIN=\"$INSTALL_PATH\""
	echo "$ . \"$INSTALL_PATH/bin/wf-env\""
fi
echo ""
echo "To learn more, visit: https://wonderful.asie.pl/wiki/"
echo "Thank you!"
echo ""

}

main
