#!/bin/sh
set -eu

HOST='https://app.leverage.computer'
TOKEN="${LEVERAGE_INSTALL_TOKEN:-}"
if [ -z "$TOKEN" ]; then
	TOKEN=''
fi

# The full mark is an interactive UTF-8 reward after a verified install. Logs,
# CI, narrow/dumb terminals, and non-UTF-8 locales get a plain manifest.
IS_TTY=0
PREMIUM=0
ANIMATE=0
if [ -t 1 ] && [ "${TERM:-}" != "dumb" ] && [ -z "${CI:-}" ]; then
	IS_TTY=1
fi
LOCALE_NAME="${LC_ALL:-${LC_CTYPE:-${LANG:-}}}"
case "$LOCALE_NAME" in
	*[Uu][Tt][Ff]-8*|*[Uu][Tt][Ff]8*) UTF8=1 ;;
	*) UTF8=0 ;;
esac
COLUMNS_VALUE="${COLUMNS:-80}"
case "$COLUMNS_VALUE" in
	""|*[!0-9]*) COLUMNS_VALUE=80 ;;
esac
if [ "$IS_TTY" -eq 1 ] && [ "$UTF8" -eq 1 ] && [ "$COLUMNS_VALUE" -ge 48 ]; then
	PREMIUM=1
	if [ "$COLUMNS_VALUE" -ge 64 ] && [ -z "${LEVERAGE_NO_ANIMATION:-}" ]; then
		ANIMATE=1
	fi
fi

if [ "$PREMIUM" -eq 1 ]; then
	B="$(printf '\033[1m')" D="$(printf '\033[2m')" N="$(printf '\033[0m')"
	if [ -z "${NO_COLOR+x}" ]; then
		case "${COLORTERM:-}" in
			truecolor|24bit) O="$(printf '\033[38;2;232;106;23m')" ;;
			*)
				case "${TERM:-}" in
					*256color*) O="$(printf '\033[38;5;208m')" ;;
					*) O="$(printf '\033[33m')" ;;
				esac
				;;
		esac
	else
		O="$B"
	fi
else
	B="" D="" N="" O=""
fi

TRANSIENT_LINES=0
CURSOR_HIDDEN=0
clear_transient() {
	if [ "$TRANSIENT_LINES" -gt 0 ]; then
		printf '\033[%sA\r\033[J' "$TRANSIENT_LINES"
		TRANSIENT_LINES=0
	fi
}

mark_row() {
	case "$1" in
		1|2|3) printf '                    ██' ;;
		4|5) printf '                   ███' ;;
		6) printf '                  ████' ;;
		7) printf '                 ▄████' ;;
		8) printf '                ██████' ;;
		9) printf '              ▄███████' ;;
		10) printf '            ▄█████████' ;;
		11) printf '         ▄▄███████████' ;;
		12) printf '   ▄▄▄▄███████████████' ;;
		13) printf '██████████████████████' ;;
	esac
}

draw_mark() {
	if [ "$ANIMATE" -eq 0 ]; then
		ROW=1
		while [ "$ROW" -le 13 ]; do
			printf '  %s' "$O"
			mark_row "$ROW"
			printf '%s\n' "$N"
			ROW=$((ROW + 1))
		done
		return
	fi

	printf '\033[?25l'
	CURSOR_HIDDEN=1
	FRAME=1
	while [ "$FRAME" -le 13 ]; do
		if [ "$FRAME" -gt 1 ]; then printf '\033[13A\r'; fi
		START_ROW=$((14 - FRAME))
		ROW=1
		while [ "$ROW" -le 13 ]; do
			printf '  %s' "$O"
			if [ "$ROW" -ge "$START_ROW" ]; then
				mark_row "$ROW"
			else
				printf '%22s' ""
			fi
			printf '%s\n' "$N"
			ROW=$((ROW + 1))
		done
		sleep 0.03
		FRAME=$((FRAME + 1))
	done
	sleep 0.12
	printf '\033[?25h'
	CURSOR_HIDDEN=0
}

die() {
	clear_transient
	printf '  %serror%s      %s\n' "$D" "$N" "$1" >&2
	if [ $# -gt 1 ]; then printf '             %s\n' "$2" >&2; fi
	exit 1
}

command -v curl >/dev/null 2>&1 || die "curl is required." \
	"install curl with your package manager, then re-run this command."

HOST_LABEL="${HOST#https://}"
HOST_LABEL="${HOST_LABEL#http://}"

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$OS" in
	darwin|linux) ;;
	*) die "unsupported OS: $OS" "leverage ships for macOS and Linux." ;;
esac

ARCH="$(uname -m)"
case "$ARCH" in
	x86_64|amd64) ARCH="x64" ;;
	aarch64|arm64) ARCH="arm64" ;;
	*) die "unsupported architecture: $ARCH" "leverage ships for x64 and arm64." ;;
esac
DEST_DIR="${LEVERAGE_INSTALL_DIR:-$HOME/.local/bin}"
TMP_DIR="$(mktemp -d)"
STAGED=""
cleanup() {
	if [ "$CURSOR_HIDDEN" -eq 1 ]; then printf '\033[?25h'; fi
	rm -rf "$TMP_DIR"
	if [ -n "$STAGED" ]; then rm -f "$STAGED"; fi
}
trap cleanup EXIT
trap 'exit 130' HUP INT TERM

if [ "$PREMIUM" -eq 1 ]; then
	printf '\n  %sfetching%s   leverage for %s/%s\n' "$D" "$N" "$OS" "$ARCH"
	TRANSIENT_LINES=1
fi
# Anonymous installs are allowed; a token, when present, still rides along.
DOWNLOAD_URL="$HOST/api/cli/download?os=$OS&arch=$ARCH"
if [ -n "$TOKEN" ]; then
	DOWNLOAD_URL="$DOWNLOAD_URL&t=$TOKEN"
fi
if ! curl -fsSL --retry 3 --connect-timeout 10 \
	"$DOWNLOAD_URL" -o "$TMP_DIR/leverage"; then
	if [ -n "$TOKEN" ]; then
		die "download failed." \
			"install commands expire after 15 minutes — copy a fresh one from Settings -> CLI devices. (or is $HOST_LABEL unreachable?)"
	else
		die "download failed." \
			"is $HOST_LABEL unreachable? try again in a moment."
	fi
fi
chmod +x "$TMP_DIR/leverage"
if [ "$PREMIUM" -eq 1 ]; then
	printf '  %sverifying%s  downloaded binary\n' "$D" "$N"
	TRANSIENT_LINES=2
fi

mkdir -p "$DEST_DIR"
STAGED="$(mktemp "$DEST_DIR/.leverage-install.XXXXXX")"
mv "$TMP_DIR/leverage" "$STAGED"

# Smoke the staged download before replacing an existing working binary.
VERSION="$("$STAGED" --version 2>/dev/null)" || die \
	"the downloaded leverage binary won't run on this machine." \
	"try again, and tell us if it keeps happening."
# Refuse to overwrite a binary that already speaks the onboard playbook with
# one that doesn't — a host serving an older R2 artifact must not silently
# downgrade a working install (docs/specs/product/onboarding-cli.md).
if [ -x "$DEST_DIR/leverage" ] \
	&& "$DEST_DIR/leverage" agent docs onboard >/dev/null 2>&1 \
	&& ! "$STAGED" agent docs onboard >/dev/null 2>&1; then
	die "download is older than your installed leverage." \
		"keeping $DEST_DIR/leverage — it already has the onboard playbook this host's binary lacks."
fi
mv "$STAGED" "$DEST_DIR/leverage"
STAGED=""

clear_transient

case "$DEST_DIR" in
	"$HOME")
		DISPLAY_DEST="~"
		EXPORT_DEST='\$HOME'
		;;
	"$HOME"/*)
		RELATIVE_DEST="${DEST_DIR#"$HOME"/}"
		DISPLAY_DEST="~/${RELATIVE_DEST}"
		EXPORT_DEST="\$HOME/${RELATIVE_DEST}"
		;;
	*)
		DISPLAY_DEST="$DEST_DIR"
		EXPORT_DEST="$DEST_DIR"
		;;
esac

VERSION_NUMBER="${VERSION#leverage }"
ON_PATH=0
case ":$PATH:" in
	*":$DEST_DIR:"*) ON_PATH=1 ;;
esac

SHELL_NAME="${SHELL:-}"
SHELL_NAME="${SHELL_NAME##*/}"
case "$SHELL_NAME" in
	zsh)
		RC_FILE="~/.zshrc"
		PATH_COMMAND="export PATH=\"$EXPORT_DEST:\$PATH\""
		PLAIN_PATH_COMMAND="export PATH=\"$DEST_DIR:\$PATH\""
		;;
	bash)
		RC_FILE="~/.bashrc"
		PATH_COMMAND="export PATH=\"$EXPORT_DEST:\$PATH\""
		PLAIN_PATH_COMMAND="export PATH=\"$DEST_DIR:\$PATH\""
		;;
	fish)
		RC_FILE="~/.config/fish/config.fish"
		PATH_COMMAND="fish_add_path \"$EXPORT_DEST\""
		PLAIN_PATH_COMMAND="fish_add_path \"$DEST_DIR\""
		;;
	*)
		RC_FILE="your shell profile"
		PATH_COMMAND="export PATH=\"$EXPORT_DEST:\$PATH\""
		PLAIN_PATH_COMMAND="export PATH=\"$DEST_DIR:\$PATH\""
		;;
esac

if [ "$PREMIUM" -eq 1 ]; then
	printf '\n'
	draw_mark
	printf '\n  %sLEVERAGE COMPUTER%s %s/ TERMINAL%s   %s%s%s\n' "$B" "$N" "$D" "$N" "$D" "$VERSION_NUMBER" "$N"
	printf '  A multiplayer computer for AI-native teams.\n'
	printf '  %sThe compounding layer for teams and agents.%s\n\n' "$D" "$N"
	printf '  %sinstalled%s   %s/leverage\n' "$D" "$N" "$DISPLAY_DEST"
	printf '  %splatform%s    %s/%s\n' "$D" "$N" "$OS" "$ARCH"
	if [ "$ON_PATH" -eq 0 ]; then
		printf '  %spath%s        %snot on PATH%s\n' "$D" "$N" "$B" "$N"
		printf '\n  %snext%s        %s%s%s\n' "$D" "$N" "$O" "$PATH_COMMAND" "$N"
		printf '              %sleverage login%s\n\n' "$O" "$N"
		printf '              %sadd the first line to %s to keep it%s\n\n' "$D" "$RC_FILE" "$N"
	else
		printf '\n  %snext%s        %sleverage login%s\n\n' "$D" "$N" "$O" "$N"
	fi
else
	printf 'LEVERAGE COMPUTER / TERMINAL %s\n' "$VERSION_NUMBER"
	printf 'A multiplayer computer for AI-native teams.\n'
	printf 'The compounding layer for teams and agents.\n'
	printf 'installed  %s/leverage\n' "$DEST_DIR"
	printf 'platform   %s/%s\n' "$OS" "$ARCH"
	if [ "$ON_PATH" -eq 0 ]; then
		printf 'warning    %s is not on PATH\n' "$DEST_DIR"
		printf 'next       %s\n' "$PLAIN_PATH_COMMAND"
	fi
	printf 'next       leverage login\n'
fi
