#!/bin/bash
# OpenClaw post-update patches
# Run after every openclaw update to reapply source fixes
# These should be removed once officially fixed upstream

OC_DIR=$(npm -g root 2>/dev/null)/openclaw/dist
PATCHED=0

# Patch 1: Preserve operator scopes with dangerouslyDisableDeviceAuth
FILE="$OC_DIR/gateway-cli-DbznSfRg.js"
if [ -f "$FILE" ] && grep -q 'if (scopes.length > 0) {' "$FILE" 2>/dev/null; then
  sed -i 's/if (scopes.length > 0) {/if (scopes.length > 0 \&\& !disableControlUiDeviceAuth) {/' "$FILE"
  echo "✅ Patch 1: Scope preservation applied"
  PATCHED=$((PATCHED + 1))
else
  echo "⏭️ Patch 1: Already applied or file changed"
fi

# Patch 2: Index deleted session transcripts in memory search
# File hashes change each release — patch all query-expansion-*.js files
P2_COUNT=0
for QE_FILE in "$OC_DIR"/query-expansion-*.js; do
  if [ -f "$QE_FILE" ] && grep -q '\.filter((name) => name\.endsWith("\.jsonl"))' "$QE_FILE" 2>/dev/null; then
    sed -i 's/\.filter((name) => name\.endsWith("\.jsonl"))/\.filter((name) => name.endsWith(".jsonl") || name.includes(".jsonl.deleted."))/' "$QE_FILE"
    echo "✅ Patch 2: Deleted transcript indexing applied to $(basename $QE_FILE)"
    PATCHED=$((PATCHED + 1))
    P2_COUNT=$((P2_COUNT + 1))
  fi
done
if [ "$P2_COUNT" -eq 0 ]; then
  echo "⏭️ Patch 2: Already applied or no matching files"
fi

echo "Patches applied: $PATCHED"

# Note: After patching, gateway needs restart
# The daily-updates.timer already restarts if OC changed
