#!/usr/bin/env bash
#
# Patch frappe_pg (excel-azmin/frappe_pg) for compatibility with Frappe 16.12+
# ─────────────────────────────────────────────────────────────────────────────
# Why this exists:
#
# frappe_pg monkey-patches `PostgresDatabase.commit()` and `.rollback()` with
# wrappers that have the OLD `(self)` signature. Frappe v16.12+ now calls
# `db.rollback(chain=True)` from `app.py:sync_database()`, which crashes
# every HTTP request with:
#
#     TypeError: patched_rollback() got an unexpected keyword argument 'chain'
#
# Symptoms: HTTP 500 on /api/method/ping, /api/resource/Sales Invoice, and
# pretty much any URL that triggers the request finalizer. We hit this on
# 2026-05-21 right after `bench install-app frappe_pg`.
#
# The fix is tiny: make the wrappers accept variadic args and forward them
# to the original functions. Submitted upstream (TODO: add PR link once
# filed at https://github.com/excel-azmin/frappe_pg/pulls), but for now
# we patch the installed copy in-place.
#
# Run this after every `bench update` or re-install of frappe_pg.
# Idempotent — re-applying produces no further changes.

set -euo pipefail

CONTAINER="${1:-erpnext-backend-1}"
APP_PATH="/home/frappe/frappe-bench/apps/frappe_pg/frappe_pg"

FILES=(
  "$APP_PATH/postgres/database_patches.py"
  "$APP_PATH/patches/postgres_fix.py"
)

echo "Patching frappe_pg in container: $CONTAINER"
echo

for f in "${FILES[@]}"; do
  echo "  → $f"

  # 1. patched_rollback / patched_commit signatures
  docker exec "$CONTAINER" sed -i \
    -e 's|def patched_rollback(self):|def patched_rollback(self, *args, **kwargs):|g' \
    -e 's|def patched_commit(self):|def patched_commit(self, *args, **kwargs):|g' \
    "$f"

  # 2. Forward args to the wrapped originals
  docker exec "$CONTAINER" sed -i \
    -e 's|return _original_rollback(self)|return _original_rollback(self, *args, **kwargs)|g' \
    -e 's|return _original_commit(self)|return _original_commit(self, *args, **kwargs)|g' \
    "$f"
done

echo
echo "Verifying:"
docker exec "$CONTAINER" grep -n 'def patched_\(rollback\|commit\)' "${FILES[@]}"
echo
echo "Restart the backend for the changes to take effect:"
echo "  docker restart $CONTAINER erpnext-frontend-1"
