#!/bin/bash
# Check for available updates — report only, don't install

set -e

echo "=== Claude Code ==="
CURRENT=$(claude --version 2>/dev/null | head -1 || echo "not installed")
LATEST=$(npm show @anthropic-ai/claude-code version 2>/dev/null || echo "unknown")

CURRENT_VER=$(echo "$CURRENT" | sed 's/ (Claude Code)//')
if [ "$CURRENT_VER" = "$LATEST" ] || [ "$LATEST" = "unknown" ]; then
    echo "✅ Up to date: $CURRENT"
else
    echo "⬆️  Update available: $CURRENT_VER → $LATEST"
    echo "   Run: npm update -g @anthropic-ai/claude-code"
fi

echo ""
echo "=== OpenClaw ==="
OC_CURRENT=$(openclaw --version 2>/dev/null | head -1 || echo "not installed")
OC_LATEST=$(npm show openclaw version 2>/dev/null || echo "unknown")

OC_CURRENT_VER=$(echo "$OC_CURRENT" | grep -oP '[\d.]+' | head -1 || echo "$OC_CURRENT")
if [ "$OC_CURRENT_VER" = "$OC_LATEST" ] || [ "$OC_LATEST" = "unknown" ]; then
    echo "✅ Up to date: $OC_CURRENT"
else
    echo "⬆️  Update available: $OC_CURRENT_VER → $OC_LATEST"
    echo "   Run: npm update -g openclaw"
fi

echo ""
echo "=== inou MCP Bundle ==="
MCPB_EXTRACT="/home/johan/clawd/inou-mcp"

if [ -f "$MCPB_EXTRACT/manifest.json" ]; then
    CURRENT_VER=$(grep -o '"version": *"[^"]*"' "$MCPB_EXTRACT/manifest.json" | cut -d'"' -f4)
    echo "Current: $CURRENT_VER"
else
    echo "Current: not installed"
fi

MCPB_URL="https://inou.com/download/inou.mcpb"
HTTP_STATUS=$(curl -sI -o /dev/null -w "%{http_code}" "$MCPB_URL" 2>/dev/null || echo "000")

if [ "$HTTP_STATUS" != "200" ]; then
    echo "Latest: (download not available)"
else
    TMP_MCPB="/tmp/inou-check.mcpb"
    TMP_DIR=$(mktemp -d)
    curl -sL -o "$TMP_MCPB" "$MCPB_URL"
    if python3 -c "import zipfile; zipfile.ZipFile('$TMP_MCPB').extractall('$TMP_DIR')" 2>/dev/null; then
        NEW_VER=$(grep -o '"version": *"[^"]*"' "$TMP_DIR/manifest.json" | cut -d'"' -f4)
        if [ "$CURRENT_VER" = "$NEW_VER" ]; then
            echo "✅ Up to date: $CURRENT_VER"
        else
            echo "⬆️  Update available: $CURRENT_VER → $NEW_VER"
        fi
    fi
    rm -rf "$TMP_DIR" "$TMP_MCPB" 2>/dev/null || true
fi
