#!/bin/bash
# Setup script for Proxmox MCP Server and workspace

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="$HOME/.env"
ENV_EXAMPLE="$SCRIPT_DIR/.env.example"
CLAUDE_CONFIG_DIR="$HOME/.config/Claude"
CLAUDE_CONFIG="$CLAUDE_CONFIG_DIR/claude_desktop_config.json"
CLAUDE_CONFIG_EXAMPLE="$SCRIPT_DIR/claude_desktop_config.json.example"

echo "🚀 Proxmox MCP Server Setup"
echo "============================"
echo ""

# Step 1: Check if .env exists
if [ ! -f "$ENV_FILE" ]; then
    echo "📝 Creating .env file from template..."
    if [ -f "$ENV_EXAMPLE" ]; then
        cp "$ENV_EXAMPLE" "$ENV_FILE"
        echo "✅ Created $ENV_FILE"
        echo "⚠️  Please edit $ENV_FILE and add your Proxmox credentials!"
    else
        # Create .env file directly if template doesn't exist
        echo "📝 Creating .env file directly..."
        cat > "$ENV_FILE" << 'EOF'
# Proxmox MCP Server Configuration
# Fill in your actual values below

# Proxmox Configuration (REQUIRED)
PROXMOX_HOST=your-proxmox-ip-or-hostname
PROXMOX_USER=root@pam
PROXMOX_TOKEN_NAME=your-token-name
PROXMOX_TOKEN_VALUE=your-token-secret

# Security Settings (REQUIRED)
# ⚠️  WARNING: Setting PROXMOX_ALLOW_ELEVATED=true enables DESTRUCTIVE operations
PROXMOX_ALLOW_ELEVATED=false

# Optional Settings
# PROXMOX_PORT=8006  # Defaults to 8006 if not specified
EOF
        echo "✅ Created $ENV_FILE"
        echo "⚠️  Please edit $ENV_FILE and add your Proxmox credentials!"
    fi
else
    echo "✅ .env file already exists at $ENV_FILE"
fi

# Step 2: Setup Claude Desktop config
echo ""
echo "📝 Setting up Claude Desktop configuration..."

if [ ! -d "$CLAUDE_CONFIG_DIR" ]; then
    mkdir -p "$CLAUDE_CONFIG_DIR"
    echo "✅ Created Claude config directory: $CLAUDE_CONFIG_DIR"
fi

if [ ! -f "$CLAUDE_CONFIG" ]; then
    echo "📝 Creating Claude Desktop config from template..."
    if [ -f "$CLAUDE_CONFIG_EXAMPLE" ]; then
        # Replace the path in the example with the actual path
        sed "s|/home/intlc/projects/proxmox|$SCRIPT_DIR|g" "$CLAUDE_CONFIG_EXAMPLE" > "$CLAUDE_CONFIG"
        echo "✅ Created $CLAUDE_CONFIG"
        echo "⚠️  Please verify the configuration and restart Claude Desktop!"
    else
        echo "❌ Template file not found: $CLAUDE_CONFIG_EXAMPLE"
        exit 1
    fi
else
    echo "✅ Claude Desktop config already exists at $CLAUDE_CONFIG"
    echo "⚠️  Skipping creation to avoid overwriting existing config"
    echo "   If you want to update it, manually edit: $CLAUDE_CONFIG"
fi

# Step 3: Install dependencies
echo ""
echo "📦 Installing workspace dependencies..."
cd "$SCRIPT_DIR"
pnpm install

echo ""
echo "✅ Setup complete!"
echo ""
echo "Next steps:"
echo "1. Edit $ENV_FILE with your Proxmox credentials"
echo "2. Verify Claude Desktop config at $CLAUDE_CONFIG"
echo "3. Restart Claude Desktop"
echo "4. Test the MCP server with: pnpm test:basic"

