#!/bin/bash
# xmem Plugin Post-Install Script
# Automatically adds 'memtap' to tools.allow if not present

CONFIG_FILE="${HOME}/.openclaw/openclaw.json"

if [ ! -f "$CONFIG_FILE" ]; then
  echo "⚠️  OpenClaw config not found at $CONFIG_FILE"
  echo "   Please add 'memtap' to tools.allow manually after setup."
  exit 0
fi

# Check if memtap is already in tools.allow
if python3 -c "
import json, sys
c = json.load(open('$CONFIG_FILE'))
allow = c.get('tools', {}).get('allow', [])
if 'memtap' in allow:
    sys.exit(0)
else:
    sys.exit(1)
" 2>/dev/null; then
  echo "✅ memtap already in tools.allow"
else
  # Add memtap to tools.allow
  python3 -c "
import json
with open('$CONFIG_FILE', 'r') as f:
    config = json.load(f)
if 'tools' not in config:
    config['tools'] = {}
if 'allow' not in config['tools']:
    config['tools']['allow'] = []
if 'memtap' not in config['tools']['allow']:
    config['tools']['allow'].append('memtap')
with open('$CONFIG_FILE', 'w') as f:
    json.dump(config, f, indent=2)
print('✅ Added memtap to tools.allow')
" 2>/dev/null

  if [ $? -ne 0 ]; then
    echo "⚠️  Could not auto-configure tools.allow"
    echo "   Please add 'memtap' to tools.allow manually:"
    echo '   tools: { allow: ["memtap"] }'
  fi
fi

# Add memtap to plugins.allow if not present
python3 -c "
import json
with open('$CONFIG_FILE', 'r') as f:
    config = json.load(f)
allow = config.get('plugins', {}).get('allow', [])
if 'memtap' not in allow:
    if 'plugins' not in config:
        config['plugins'] = {}
    if 'allow' not in config['plugins']:
        config['plugins']['allow'] = []
    config['plugins']['allow'].append('memtap')
    with open('$CONFIG_FILE', 'w') as f:
        json.dump(config, f, indent=2)
    print('✅ Added memtap to plugins.allow')
else:
    print('✅ memtap already in plugins.allow')
" 2>/dev/null

echo ""
echo "🧠 xmem Plugin installed!"
echo ""
echo "Next steps:"
echo "  1. Get your API key at https://xmem.space/dashboard"
echo "  2. Configure: openclaw config set plugins.entries.memtap.config.apiKey 'mt_live_xxx'"
echo "  3. Restart: openclaw gateway restart"
echo ""
