#!/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=20260619
BOOTSTRAP_DOWNLOAD_PATH="https://wonderful.asie.pl/bootstrap"
INSTALL_PATH="/opt/wonderful"

main() {

# Color support

C_RESET=""
C_STATUS="<~>"
C_SUCCESS="^_^"
C_ERROR="[!]"

if [[ -n "${BASH_VERSION-}" ]]; then
	if [[ -z "${NO_COLOR-}" ]] && command -v tput >/dev/null; then
		C_RESET=$(tput sgr0)
		C_STATUS=$(tput setaf 7)"$C_STATUS$C_RESET"
		C_SUCCESS=$(tput setaf 10)"$C_SUCCESS$C_RESET"
		C_ERROR=$(tput setaf 9)"$C_ERROR$C_RESET"
		echo -n "$C_RESET"
	fi
fi

# 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() {
	local TMPFILE="$(mktemp)"

	if [[ -f "$1" ]]; then
		if [[ ! -w "$1" ]]; then
			echo "$C_ERROR $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
	if [[ -n "$2" ]]; then
		echo "# Begin Wonderful Toolchain wf-installer code" >> "$TMPFILE"
		echo "$2" >> "$TMPFILE"
		echo "# End Wonderful Toolchain wf-installer code" >> "$TMPFILE"
	fi

	mv "$TMPFILE" "$1" || echo "$C_ERROR $1 is not writable, skipping..."
}

download_file() {
	case "$DOWNLOAD_TOOL" in
		curl)
			curl -o "$2" "$1"
			;;
		wget)
			wget -O "$2" "$1"
			;;
	esac
}

create_directory() {
	if [[ ! -w "$1" ]]; then
		local PATH_PARENT="$(dirname "$1")"
		if [[ -w "$PATH_PARENT" ]]; then
			mkdir -p "$1"
		else
			SUDO_TOOL="$(find_one_of_tools sudo run0 doas)"
			if [[ -z "$SUDO_TOOL" ]]; then
				echo -e "$C_ERROR No privilege escalation tool found. Could not create $1. Please install sudo (recommended), run0 or doas."
				exit 1
			fi
			echo -e "$C_ERROR Privilege escalation required to access $1..."
			"$SUDO_TOOL" mkdir -p "$1" && "$SUDO_TOOL" chown -R "$USER" "$1"
		fi
	fi
}

# Script

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

PLATFORM="$(uname -s)"
TARGET="$PLATFORM/$(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"
		;;
	Darwin/arm64)
		DOWNLOAD_PATH="$BOOTSTRAP_DOWNLOAD_PATH/wf-bootstrap-darwin-aarch64.tar.gz"
		# FIXME: Support alternate paths on macOS
		SKIP_PATH_CHOICE=1
		;;
	*)
		echo -e "$C_ERROR Unsupported operating system/architecture pair ($TARGET)."
		exit 1
		;;
esac

echo "$C_STATUS 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 "$C_ERROR bash is not installed. Please install bash before continuing."
	VERIFIED=0
fi

for TOOL in chown ls make mkdir mktemp realpath sed tar; do
	if ! command -v "$TOOL" >/dev/null; then
		echo -e "$C_ERROR $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 "$C_ERROR No supported download tool found. Please install curl or wget before continuing."
	VERIFIED=0
fi

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

set_custom_install_path() {
	read -p "Enter path: " CUSTOM_INSTALL_PATH </dev/tty
	if [[ "$CUSTOM_INSTALL_PATH" = "/" ]]; then
		echo "$C_ERROR Installing to $CUSTOM_INSTALL_PATH is not a good idea."
		return 1
	elif [[ -n "$CUSTOM_INSTALL_PATH" ]]; then
		INSTALL_PATH="$(realpath "$CUSTOM_INSTALL_PATH")"
		return 0
	else
		return 1
	fi
}

if [[ "$OSTYPE" == linux-android* ]]; then
	INSTALL_PATH="$HOME/.wonderful"
fi

if [[ -z "$SKIP_PATH_CHOICE" ]]; then
	echo ""
	echo "Please choose the installation path:"
	if [[ "$OSTYPE" == linux-android* ]]; then
		echo "1) $INSTALL_PATH [default, experimental]"
		echo "2) User-specified path [experimental]"

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

			case "$choice" in
				""|1)
					break
					;;
				2)
					if set_custom_install_path; then
						break
					fi
					;;
			esac
		done
	else
		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)
					if set_custom_install_path; then
						break
					fi
					;;
			esac
		done
	fi
fi

if [[ -n "$(ls -A "$INSTALL_PATH" 2>/dev/null)" ]]; then
	echo "$C_ERROR 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
	echo ""
	echo "$C_STATUS Downloading bootstrap..."

	BOOTSTRAP_PATH="$(mktemp)"
	trap 'rm "$BOOTSTRAP_PATH"' EXIT
	download_file "$DOWNLOAD_PATH" "$BOOTSTRAP_PATH"

	create_directory "$INSTALL_PATH"

	echo ""
	echo "$C_STATUS Extracting bootstrap..."

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

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

	if [[ "$PLATFORM" = "Darwin" ]]; then
		echo "$C_STATUS Self-signing wf-pacman..."
		codesign --remove-signature "$INSTALL_PATH/bin/wf-pacman"
		codesign -s - "$INSTALL_PATH/bin/wf-pacman"
	fi

	echo "$C_STATUS 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- programs to PATH. [default, recommended]"
echo "2) Export WONDERFUL_TOOLCHAIN, add wf- programs and all toolchains to PATH."
echo "3) Export WONDERFUL_TOOLCHAIN, provide wf-env to configure environment variables."
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 "$C_STATUS 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 "$C_SUCCESS 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
