#!/bin/bash
# UClaude Updater — automatic Claude Code patch updater
# Usage: sudo bash claude/uclaude_update.sh [--check] [--force] [--settings-only]
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(dirname "$SCRIPT_DIR")"
cd "$REPO_ROOT"

# Fetch latest commit (shallow — no history)
git fetch --depth 1 origin master 2>/dev/null && git reset --hard origin/master 2>/dev/null || git pull --quiet 2>/dev/null || true

# Update sparse checkout to include latest version directory
if [ -f claude/releases/index.json ] && git config core.sparseCheckout 2>/dev/null | grep -q true; then
    VER=$(python3 -c "import json; print(json.load(open('claude/releases/index.json'))['latest'])" 2>/dev/null)
    if [ -n "$VER" ]; then
        git sparse-checkout add "claude/releases/v${VER}" 2>/dev/null
        git checkout 2>/dev/null || true
    fi
fi

# Run updater
if [ "$(id -u)" -eq 0 ]; then
    python3 claude/uclaude_updater.py "$@"
else
    echo "Root privileges required. Re-running with sudo..."
    sudo python3 claude/uclaude_updater.py "$@"
fi
