#!/bin/sh
# LXI CLI user installation for Linux and macOS. No sudo or system Python changes.
set -eu

case "$(uname -s)" in Linux|Darwin) ;; *) echo 'Use install-lxi.ps1 on Windows.' >&2; exit 1 ;; esac
lxi_root=${LXI_INSTALL_DIR:-"$HOME/.local/share/lxi"}
lxi_bin=${LXI_BIN_DIR:-"$HOME/.local/bin"}
mkdir -p "$lxi_root/installer" "$lxi_bin"
export UV_TOOL_DIR="$lxi_root/tools"
export UV_TOOL_BIN_DIR="$lxi_bin"
export UV_PYTHON_INSTALL_DIR="$lxi_root/python"
export UV_CACHE_DIR="$lxi_root/cache"
lxi_uv="$lxi_root/installer/uv"

if [ ! -x "$lxi_uv" ]; then
    echo 'Installing the LXI runtime manager ...'
    lxi_setup=$(mktemp "$lxi_root/installer/bootstrap.XXXXXX")
    trap 'rm -f "$lxi_setup"' EXIT HUP INT TERM
    curl --proto '=https' --tlsv1.2 -fsSL https://astral.sh/uv/install.sh -o "$lxi_setup"
    UV_UNMANAGED_INSTALL="$lxi_root/installer" sh "$lxi_setup"
fi

echo 'Installing LXI CLI (Python is downloaded automatically if needed) ...'
"$lxi_uv" tool install --python 3.12 --upgrade 'https://lxi.be/downloads/lxi_cli-1.1.0-py3-none-any.whl'
if [ "${LXI_NO_MODIFY_PATH:-0}" != 1 ]; then
    lxi_path_marker="$lxi_root/installer/path-configured"
    if [ ! -f "$lxi_path_marker" ] || [ "$(cat "$lxi_path_marker")" != "$lxi_bin" ]; then
        SHELL="${SHELL:-/bin/bash}" "$lxi_uv" tool update-shell
        printf '%s' "$lxi_bin" > "$lxi_path_marker"
    fi
fi
"$lxi_bin/lxi" --help >/dev/null
printf '\nLXI CLI installed successfully.\nOpen a new terminal, then run: lxi auth login\n'
printf 'For this terminal: export PATH="%s:$PATH"\n' "$lxi_bin"
