#!/bin/bash
# Installs cont8nuum by asking a few questions, one at a time, then doing
# what the answers say: the packages it builds against, the build, the
# install, and the pieces around it (run-time packages, the wallet).
#
#   ./install.sh                 ask, then do it
#   ./install.sh --dry-run       ask, then only say what would be run
#   ./install.sh --yes           no questions: the recommended answers
#
# Any answer can be given ahead, and is then not asked:
#   --where install|try          /usr/local for your session, or .prefix
#   --apps all|none|LIST         the apps beside the desktop: files, photos,
#                                video, news, weather, tailscale, tiles, lua,
#                                cirrus
#                                (commas between)
#   --packages yes|no            install the build packages with zypper
#   --runtime yes|no             the cont8nuum-deps package (install only)
#   --wallet yes|no              build the oo7 wallet (install only)
#   --xr yes|no                  Monado and the OpenXR loader, for VR games
#                                in XR glasses
#   --account-url URL|none       the cont8nuum account's site (default
#                                https://c8.lowtide.sbs)
#
# It only knows openSUSE's package names (DEPENDENCIES.md has what each
# is for). The steps themselves are build.sh and the scripts in
# packaging/, which can be run by hand instead.
set -euo pipefail

top=$(cd "$(dirname "$0")" && pwd)

# What cont8nuum builds against: DEPENDENCIES.md's list. Keep the two in
# step.
build_packages="gcc meson ninja
	wlroots-devel wayland-devel wayland-protocols-devel libinput-devel
	libxkbcommon-devel libpixman-1-0-devel fontconfig-devel
	cairo-devel pango-devel glib2-devel gdk-pixbuf-devel librsvg-devel
	libxcb-devel xcb-util-wm-devel pam-devel libpulse-devel
	libsecret-devel polkit-devel
	Mesa-libGLESv2-devel Mesa-libEGL-devel libdrm-devel"

# The apps, apart from the desktop (the compositor, the shell, PC
# settings, the live tiles), which runs without any of them: build.sh's
# names, what each is, and the packages only it builds against
app_ids=(files photos video news weather tailscale tiles lua cirrus)
app_names=("Files" "Photos" "Video" "News" "Weather" "Tailscale" "Tile maker" "Lua apps" "Cirrus")
app_about=(
	"The file manager, archives too, and the file picker other apps get. The Files tile on a new Start opens it."
	"The picture viewer."
	"The video player, 3D and all-round videos too."
	"The feed reader, with its live tile."
	"Forecasts, radar and alerts (the US), with its live tile."
	"Tailscale: devices, exit node, account, with its live tile."
	"Start tiles of your own, and for your games."
	"c8-lua: apps and live tiles written in Lua, with no build step; with Calculator, Clock, Notes, Text editor, Mines, Merge and Reversi."
	"An app for Bluesky: your timeline, feeds and notifications, with its live tile."
)
app_packages=("libarchive-devel" "libglycin-devel gexiv2-devel" "mpv-devel 'pkgconfig(libavformat)' 'pkgconfig(libavcodec)' 'pkgconfig(libavutil)'" "libxml2-devel" "" "" "" "" "")
wallet_packages="cargo rust curl patch"
runtime_packages="rpm-build"
# Monado's and xrizer's, for build.sh --xr (xr/; DEPENDENCIES.md)
xr_packages="cmake glslang-devel shaderc eigen3-devel libusb-1_0-devel
libhidapi-devel libbsd-devel cJSON-devel sdl2-compat-devel vulkan-devel
libXrandr-devel Mesa-libGLESv3-devel cargo rust"

where= packages= runtime= wallet= account= apps= xr=
dry=false yes=false

usage() {
	sed -n '2,23p' "$0" | sed 's/^# \{0,1\}//'
}

while [ $# -gt 0 ]; do
	case "$1" in
	--dry-run) dry=true; shift ;;
	--yes|-y) yes=true; shift ;;
	--where) where=$2; shift 2 ;;
	--apps) apps=$2; shift 2 ;;
	--packages) packages=$2; shift 2 ;;
	--runtime) runtime=$2; shift 2 ;;
	--wallet) wallet=$2; shift 2 ;;
	--xr) xr=$2; shift 2 ;;
	--account-url) account=$2; shift 2 ;;
	-h|--help) usage; exit 0 ;;
	*) echo "install.sh: unknown option '$1'" >&2; usage >&2; exit 2 ;;
	esac
done

check() { # NAME VALUE ALLOWED...
	local name=$1 value=$2 a
	shift 2
	[ -z "$value" ] && return 0
	for a in "$@"; do
		[ "$value" = "$a" ] && return 0
	done
	echo "install.sh: --$name is one of: $*" >&2
	exit 2
}
check where "$where" install try
check packages "$packages" yes no
check runtime "$runtime" yes no
check wallet "$wallet" yes no
check xr "$xr" yes no

# Colours, when there is a terminal that wants them
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] && [ "${TERM:-dumb}" != dumb ]; then
	bold=$'\e[1m' dim=$'\e[2m' accent=$'\e[38;5;39m' green=$'\e[32m'
	red=$'\e[31m' invert=$'\e[7m' off=$'\e[0m'
else
	bold= dim= accent= green= red= invert= off=
fi

# Asking. One question at a time: a short header, the question, numbered
# options each with a line saying what it means, the recommended one
# first. Up and Down (or j, k) move, a number picks, Enter takes it, Esc
# or q leaves. The answer is left in $answer (the option's number, from
# 1) and, for an option that takes text, what was typed in $typed.

answer=1 typed=

# The lines of one drawing of the options, so it can be drawn over
drawn=0

draw_options() { # CURRENT LABEL DESC [LABEL DESC]...
	local current=$1 i=1 line wrap
	shift
	wrap=$(($(tput cols 2>/dev/null || echo 80) - 6))
	[ "$wrap" -lt 30 ] && wrap=30
	[ "$wrap" -gt 74 ] && wrap=74
	if [ "$drawn" -gt 0 ]; then
		printf '\e[%dA' "$drawn"
	fi
	drawn=0
	while [ $# -gt 0 ]; do
		if [ "$i" = "$current" ]; then
			printf '\e[2K%s❯ %d. %s%s\n' "$accent$bold" "$i" "$1" "$off"
		else
			printf '\e[2K  %d. %s\n' "$i" "$1"
		fi
		# Wrapped here, to the terminal: a line the terminal wraps itself
		# isn't counted, and the next drawing would start too low
		while IFS= read -r line; do
			printf '\e[2K     %s%s%s\n' "$dim" "$line" "$off"
			drawn=$((drawn + 1))
		done < <(printf '%s\n' "$2" | fold -s -w "$wrap")
		drawn=$((drawn + 1))
		i=$((i + 1))
		shift 2
	done
	printf '\e[2K\n\e[2K%sEnter to select · ↑/↓ to move · Esc to quit%s\n' "$dim" "$off"
	drawn=$((drawn + 2))
}

ask() { # HEADER QUESTION LABEL DESC [LABEL DESC]...
	local header=$1 question=$2 count key rest
	shift 2
	count=$(($# / 2))
	answer=1
	if $yes; then
		return 0
	fi
	if ! [ -t 0 ] || ! [ -t 1 ]; then
		echo "install.sh: no terminal to ask on. Give the answers as options, or --yes (see --help)." >&2
		exit 2
	fi
	printf '\n%s %s %s\n\n%s%s%s\n\n' "$invert" "$header" "$off" "$bold" "$question" "$off"
	drawn=0
	printf '\e[?25l' # no cursor while choosing
	while true; do
		draw_options "$answer" "$@"
		IFS= read -rsn1 key || key=q
		case "$key" in
		$'\e')
			# An arrow is Esc and two more; Esc alone is nothing more
			rest=
			IFS= read -rsn2 -t 0.05 rest || true
			case "$rest" in
			'[A'|'OA') key=k ;;
			'[B'|'OB') key=j ;;
			'') key=q ;;
			*) key= ;;
			esac
			;;
		esac
		case "$key" in
		k) answer=$(((answer + count - 2) % count + 1)) ;;
		j) answer=$((answer % count + 1)) ;;
		[1-9])
			if [ "$key" -le "$count" ]; then
				answer=$key
				draw_options "$answer" "$@"
				break
			fi
			;;
		'') break ;; # Enter
		q)
			printf '\e[?25h\n%sNothing was changed.%s\n' "$dim" "$off"
			exit 130
			;;
		esac
	done
	printf '\e[?25h'
	# Leave only what was chosen where the options were
	local label=$(((answer - 1) * 2 + 1))
	printf '\e[%dA\e[J' "$drawn"
	printf '%s❯ %s%s\n' "$green" "${!label}" "$off"
}

# Several of a list: Space ticks the one the cursor is on, a number ticks
# that one, a ticks all or none, Enter takes them. picked[] says which,
# and starts as what is ticked to begin with.

picked=()

draw_many() { # CURRENT LABEL DESC [LABEL DESC]...
	local current=$1 i=1 line wrap box
	shift
	wrap=$(($(tput cols 2>/dev/null || echo 80) - 10))
	[ "$wrap" -lt 30 ] && wrap=30
	[ "$wrap" -gt 70 ] && wrap=70
	if [ "$drawn" -gt 0 ]; then
		printf '\e[%dA' "$drawn"
	fi
	drawn=0
	while [ $# -gt 0 ]; do
		box="[ ]"
		[ "${picked[$((i - 1))]}" = 1 ] && box="[✔]"
		if [ "$i" = "$current" ]; then
			printf '\e[2K%s❯ %d. %s %s%s\n' "$accent$bold" "$i" "$box" "$1" "$off"
		else
			printf '\e[2K  %d. %s %s\n' "$i" "$box" "$1"
		fi
		while IFS= read -r line; do
			printf '\e[2K         %s%s%s\n' "$dim" "$line" "$off"
			drawn=$((drawn + 1))
		done < <(printf '%s\n' "$2" | fold -s -w "$wrap")
		drawn=$((drawn + 1))
		i=$((i + 1))
		shift 2
	done
	printf '\e[2K\n\e[2K%sSpace to tick · a for all or none · ↑/↓ to move · Enter when done · Esc to quit%s\n' "$dim" "$off"
	drawn=$((drawn + 2))
}

ask_many() { # HEADER QUESTION LABEL DESC [LABEL DESC]...
	local header=$1 question=$2 count key rest current=1 i any chosen
	shift 2
	count=$(($# / 2))
	if $yes; then
		return 0
	fi
	if ! [ -t 0 ] || ! [ -t 1 ]; then
		echo "install.sh: no terminal to ask on. Give the answers as options, or --yes (see --help)." >&2
		exit 2
	fi
	printf '\n%s %s %s\n\n%s%s%s\n\n' "$invert" "$header" "$off" "$bold" "$question" "$off"
	drawn=0
	printf '\e[?25l'
	while true; do
		draw_many "$current" "$@"
		IFS= read -rsn1 key || key=q
		case "$key" in
		$'\e')
			rest=
			IFS= read -rsn2 -t 0.05 rest || true
			case "$rest" in
			'[A'|'OA') key=k ;;
			'[B'|'OB') key=j ;;
			'') key=q ;;
			*) key=none ;;
			esac
			;;
		esac
		case "$key" in
		k) current=$(((current + count - 2) % count + 1)) ;;
		j) current=$((current % count + 1)) ;;
		' ') picked[current - 1]=$((1 - picked[current - 1])) ;;
		[1-9])
			if [ "$key" -le "$count" ]; then
				current=$key
				picked[current - 1]=$((1 - picked[current - 1]))
			fi
			;;
		a)
			any=0
			for i in "${picked[@]}"; do
				[ "$i" = 1 ] && any=1
			done
			for ((i = 0; i < count; i++)); do
				picked[i]=$((1 - any))
			done
			;;
		'') break ;;
		q)
			printf '\e[?25h\n%sNothing was changed.%s\n' "$dim" "$off"
			exit 130
			;;
		esac
	done
	printf '\e[?25h\e[%dA\e[J' "$drawn"
	chosen=
	for ((i = 0; i < count; i++)); do
		if [ "${picked[i]}" = 1 ]; then
			rest=$((i * 2 + 1))
			chosen="$chosen${chosen:+, }${!rest}"
		fi
	done
	printf '%s❯ %s%s\n' "$green" "${chosen:-None: the desktop alone}" "$off"
}

trap '[ -t 1 ] && printf "\e[?25h"' EXIT

# Where this is being run

distro=other
if [ -r /etc/os-release ]; then
	# shellcheck disable=SC1091
	. /etc/os-release
	case " ${ID:-} ${ID_LIKE:-} " in
	*suse*) distro=opensuse ;;
	esac
fi
if [ "$(id -u)" = 0 ]; then
	echo "install.sh: run it as yourself, not root. It asks for your password when a step needs it." >&2
	exit 1
fi

printf '\n%s%scont8nuum%s  a Windows 8 style desktop for Wayland\n' "$bold" "$accent" "$off"
printf '%sA few questions, then it builds. Nothing is changed before you say so.%s\n' "$dim" "$off"

# The questions

if [ -z "$where" ]; then
	ask "Where" "Where should cont8nuum go?" \
		"Install it (Recommended)" "Into /usr/local, as a desktop to pick when you log in. Asks for your password." \
		"Only try it" "Built into .prefix in this folder and run in a window. Nothing outside this folder is touched."
	case $answer in 1) where=install ;; 2) where=try ;; esac
fi

# Which apps: all of them unless said
picked=()
for id in "${app_ids[@]}"; do
	case "$apps" in
	''|all) picked+=(1) ;;
	none) picked+=(0) ;;
	*)
		case ",$apps," in
		*",$id,"*) picked+=(1) ;;
		*) picked+=(0) ;;
		esac
		;;
	esac
done
if [ -n "$apps" ] && [ "$apps" != all ] && [ "$apps" != none ]; then
	for id in ${apps//,/ }; do
		case " ${app_ids[*]} " in
		*" $id "*) ;;
		*)
			echo "install.sh: no app called '$id' (there are: ${app_ids[*]})" >&2
			exit 2
			;;
		esac
	done
fi
if [ -z "$apps" ]; then
	options=()
	for i in "${!app_ids[@]}"; do
		options+=("${app_names[$i]}" "${app_about[$i]}")
	done
	ask_many "Apps" "Which apps should come with the desktop?" "${options[@]}"
fi
apps=
app_extra=
for i in "${!app_ids[@]}"; do
	if [ "${picked[$i]}" = 1 ]; then
		apps="$apps${apps:+,}${app_ids[$i]}"
		app_extra="$app_extra ${app_packages[$i]}"
	fi
done
[ -z "$apps" ] && apps=none
all_list=$(IFS=,; echo "${app_ids[*]}")
[ "$apps" = "$all_list" ] && apps=all

if [ -z "$packages" ]; then
	if [ "$distro" = opensuse ]; then
		ask "Packages" "Install the packages it builds against?" \
			"Yes, with zypper (Recommended)" "Compiler, meson, wlroots and the other -devel packages. Ones you have are left alone." \
			"No, I have them" "Skip this. The build stops and says so if one is missing."
		case $answer in 1) packages=yes ;; 2) packages=no ;; esac
	else
		packages=no
	fi
fi

if [ "$where" = install ]; then
	if [ -z "$runtime" ]; then
		if [ "$distro" = opensuse ]; then
			ask "Run time" "Install what cont8nuum uses while it runs?" \
				"Yes, as one package (Recommended)" "Builds cont8nuum-deps, a package of only dependencies (portals, sound, thumbnails...), so zypper installs them and never removes them as unneeded." \
				"No" "Skip it. Parts will be missing until the packages in DEPENDENCIES.md are there."
			case $answer in 1) runtime=yes ;; 2) runtime=no ;; esac
		else
			runtime=no
		fi
	fi
	if [ -z "$wallet" ]; then
		ask "Wallet" "Build the wallet for saved passwords?" \
			"Yes (Recommended)" "oo7 0.6 from source, with cargo: a few minutes. Opens with your login password; browsers and online accounts keep theirs in it." \
			"No" "Skip it. Without a wallet apps can't save passwords, and with an older oo7 Chromium and Electron apps can hang at start."
		case $answer in 1) wallet=yes ;; 2) wallet=no ;; esac
	fi
else
	runtime=no
	wallet=no
fi

if [ -z "$xr" ]; then
	ask "VR" "Add VR games for XR glasses?" \
		"No (Recommended)" "XR works the same without it: windows, Start and 3D video in the glasses." \
		"Yes, build Monado" "Monado drives the glasses and VR games (OpenXR, SteamVR's through xrizer) play in the same space as the windows. Fetched from upstream and built: ten minutes or more."
	case $answer in 1) xr=no ;; 2) xr=yes ;; esac
fi

if [ -z "$account" ]; then
	ask "Account" "Which cont8nuum account site should PC settings sign in to?" \
		"c8.lowtide.sbs (Recommended)" "The cont8nuum account: your settings and pictures on every PC you sign in to." \
		"Another site" "A c8-online site you or someone you trust runs. You type its address next." \
		"None" "The account, and settings sync with it, are left out. Everything else works the same."
	case "$answer" in
	1) account=https://c8.lowtide.sbs ;;
	2)
		printf '%sAddress (https://...): %s' "$bold" "$off"
		IFS= read -r account
		;;
	*) account=none ;;
	esac
fi
case "$account" in
*"'"*|*[[:space:]]*)
	echo "install.sh: that isn't an address" >&2
	exit 2
	;;
''|none) account= ;;
https://*) ;;
http://127.0.0.1*|http://localhost*) ;;
*)
	echo "install.sh: the account's address starts with https:// (plain http only for this machine itself)" >&2
	exit 2
	;;
esac

# What will be done, as the commands themselves

steps=()   # what each does, in words
commands=() # and the command

add() {
	steps+=("$1")
	commands+=("$2")
}

build_list=$(echo $build_packages $app_extra)
apps_arg=
[ "$apps" != all ] && apps_arg=" --apps $apps"
[ "$xr" = yes ] && apps_arg="$apps_arg --xr"
if [ "$packages" = yes ]; then
	extra=
	[ "$wallet" = yes ] && extra=" $wallet_packages"
	[ "$runtime" = yes ] && extra="$extra $runtime_packages"
	[ "$xr" = yes ] && extra="$extra $(echo $xr_packages)"
	zyp="sudo zypper install"
	$yes && zyp="sudo zypper --non-interactive install"
	add "Install the build packages" "$zyp $build_list$extra"
fi
# Always said, even empty: build.sh's own default is the live site
env_prefix="C8_ACCOUNT_URL='$account' "
if [ "$where" = install ]; then
	add "Build and install into /usr/local" "${env_prefix}./build.sh --install$apps_arg"
	[ "$wallet" = yes ] && add "Build and install the wallet (oo7)" "packaging/build-oo7.sh"
	[ "$runtime" = yes ] && add "Install what it uses while running" "packaging/make-deps-rpm.sh --install"
else
	add "Build into .prefix" "${env_prefix}./build.sh$apps_arg"
fi

printf '\n%s Plan %s\n\n' "$invert" "$off"
for i in "${!steps[@]}"; do
	printf '  %d. %s\n     %s%s%s\n' "$((i + 1))" "${steps[$i]}" "$dim" "${commands[$i]}" "$off"
done
if [ "$distro" != opensuse ]; then
	printf '\n%sThis isn'"'"'t openSUSE, so no packages are installed for you.\nDEPENDENCIES.md lists what is needed, by openSUSE'"'"'s names.%s\n' "$dim" "$off"
fi
if [ "$where" = install ]; then
	printf '\n%sThe few files it writes outside /usr/local (PAM rules, portal settings,\na udev rule) are listed at the end of DEPENDENCIES.md.%s\n' "$dim" "$off"
fi

if $dry; then
	printf '\n%sA dry run: nothing was run.%s\n' "$dim" "$off"
	exit 0
fi

ask "Go" "Go ahead?" \
	"Yes, do it" "Runs the steps above, in order, and stops at the first that fails." \
	"No" "Leave without changing anything."
if [ "$answer" != 1 ]; then
	printf '%sNothing was changed.%s\n' "$dim" "$off"
	exit 0
fi

# Doing it

cd "$top"
log=$top/install.log
: >"$log"
if printf '%s\n' "${commands[@]}" | grep -q -e sudo -e '--install'; then
	# Once now, not in the middle of a long build
	sudo -v
fi

for i in "${!steps[@]}"; do
	printf '\n%s[%d/%d] %s%s\n%s$ %s%s\n' "$bold$accent" "$((i + 1))" "${#steps[@]}" \
		"${steps[$i]}" "$off" "$dim" "${commands[$i]}" "$off"
	# To the screen and the log both; the step's own status, not tee's
	set +e
	bash -c "${commands[$i]}" 2>&1 | tee -a "$log"
	status=${PIPESTATUS[0]}
	set -e
	if [ "$status" != 0 ]; then
		printf '\n%sThat step failed (status %d).%s What it said is above and in %s.\n' \
			"$red$bold" "$status" "$off" "$log"
		printf 'Once it is put right, run ./install.sh again: steps already done are quick the second time.\n'
		exit "$status"
	fi
done

printf '\n%s%sDone.%s\n\n' "$bold" "$green" "$off"
if [ "$where" = install ]; then
	cat <<EOF
Log out, and pick cont8nuum as the session in SDDM (the menu at the
bottom left of the login screen).

  Tap Super for Start. Super+C for the charms, Super+I for settings.
  README.md has the other keys.
EOF
else
	# as build.sh: lib64, or the multiarch folder on Debian and Ubuntu
	multiarch=$(${CC:-cc} -print-multiarch 2>/dev/null || true)
	cat <<EOF
To run it in a window inside the desktop you have now:

  export PATH="$top/.prefix/bin:\$PATH" LD_LIBRARY_PATH="$top/.prefix/lib64:${multiarch:+$top/.prefix/lib/$multiarch:}$top/.prefix/lib"
  export XDG_DATA_DIRS="$top/.prefix/share:\${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
  c8

To install it for real later: ./install.sh
EOF
fi
