#!/usr/bin/env bash
set -Eeuo pipefail

DATA_ROOT="${DATA_ROOT:-/root/data}"
LEHOME_CLI_REPO_URL="${LEHOME_CLI_REPO_URL:-https://github.com/sudo-yf/lehome.git}"
TARGET_DIR="${TARGET_DIR:-$DATA_ROOT/lehome}"

mkdir -p "$DATA_ROOT"

if [[ -d "$TARGET_DIR/.git" ]]; then
  echo ">>> 检测到已有 LeHome CLI 仓库，正在更新..."
  git -C "$TARGET_DIR" fetch origin
  git -C "$TARGET_DIR" pull --ff-only origin main
else
  echo ">>> 正在拉取 LeHome CLI 仓库..."
  git clone "$LEHOME_CLI_REPO_URL" "$TARGET_DIR"
fi

export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
if ! command -v uv >/dev/null 2>&1; then
  echo ">>> 未检测到 uv，正在安装..."
  curl -LsSf https://astral.sh/uv/install.sh | sh
  export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
fi

echo ">>> 正在通过 uv 启动 LeHome CLI..."
exec uv tool run --refresh --from "$TARGET_DIR" lehome "$@"
