#!/usr/bin/env bash
# onx-snappymail-secfetch-disable — SnappyMail Sec-Fetch reject'i PHP-level disable
#
# SnappyMail RainLoop\Http\SecFetch::isCrossSite() veya
# RainLoop\Service::handleSecFetch() cross-site request'leri reddeder.
# Config'te secfetch_allow directive var ama bazı kombinasyonlar parse edilmez.
# Bu script:
#   1. /usr/share/snappymail/snappymail/v/X.Y.Z/app/libraries/snappymail/http/secfetch.php
#      içindeki isAllowed() / parse() metodlarında "cross-site" reject'i bypass eder
#   2. Plus Service.php'de "Disallowed Sec-Fetch" throw kısmını comment out
#
# Backup .bak.v82.8 alır.
# Idempotent (zaten patch'lenmişse skip).

set -euo pipefail

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
[[ -f "${SCRIPT_DIR}/_lib/common.sh" ]] && source "${SCRIPT_DIR}/_lib/common.sh" || true

# SnappyMail dizinleri (versiyon-bağımsız glob)
for SVC in /usr/share/snappymail/snappymail/v/*/app/libraries/RainLoop/Service.php; do
    [[ -f "$SVC" ]] || continue

    # Idempotent check
    if grep -q "// ONOX_SECFETCH_DISABLED" "$SVC"; then
        echo "  ✓ Already patched: $SVC"
        continue
    fi

    # Backup
    cp "$SVC" "${SVC}.bak.v82.8"

    # SecFetch::handle() veya benzer reject kodunu bul + comment out
    # Yaklaşık satır 110-130 arası "Disallowed Sec-Fetch" log + throw/die
    python3 <<PYEOF
import re
with open('$SVC') as f:
    c = f.read()

# Pattern: try { SecFetch::handle($this->oHttp); } catch ... throw veya logException
# Veya: if (!SecFetch::isAllowed()) { ... }
# Tek satır guard: "Disallowed Sec-Fetch" log mesajı içeren block'u no-op yap

new = re.sub(
    r'(\s*)(\\?RainLoop\\?Http\\?SecFetch::handle\([^)]+\);)',
    r'\1// ONOX_SECFETCH_DISABLED v82.8: bypass cross-site reject\n\1// \2',
    c
)

# Plus isAllowed/isCrossSite check'leri
new = re.sub(
    r'(if\s*\(\s*\\?SecFetch::isAllowed\([^)]*\)\s*===?\s*false\s*\)\s*\{)',
    r'// ONOX_SECFETCH_DISABLED \1',
    new
)

if new != c:
    with open('$SVC', 'w') as f:
        f.write(new)
    print(f"  ✓ Patched: $SVC")
else:
    print(f"  ⚠ No SecFetch call found in: $SVC")
PYEOF
done

# Plus secfetch.php — isAllowed() her zaman true döner
for SF in /usr/share/snappymail/snappymail/v/*/app/libraries/snappymail/http/secfetch.php; do
    [[ -f "$SF" ]] || continue

    if grep -q "// ONOX_SECFETCH_BYPASS" "$SF"; then
        echo "  ✓ Already patched: $SF"
        continue
    fi

    cp "$SF" "${SF}.bak.v82.8"

    python3 <<PYEOF
import re
with open('$SF') as f:
    c = f.read()

# isAllowed metodunun başına "return true" ekle
new = re.sub(
    r'(public\s+static\s+function\s+isAllowed\s*\([^)]*\)\s*:\s*\w+\s*\{)',
    r'\1\n        return true; // ONOX_SECFETCH_BYPASS v82.8',
    c
)
# Plus handle() metodu
new = re.sub(
    r'(public\s+static\s+function\s+handle\s*\([^)]*\)\s*[:\w\s]*\{)',
    r'\1\n        return; // ONOX_SECFETCH_BYPASS v82.8',
    new
)

if new != c:
    with open('$SF', 'w') as f:
        f.write(new)
    print(f"  ✓ Patched: $SF")
PYEOF
done

# Cache temizle (PHP opcache + SnappyMail data cache)
rm -rf /usr/share/snappymail/data/_data_/_default_/cache/* 2>/dev/null

# PHP-FPM restart (opcache fresh)
for ver in 82 83; do
    systemctl is-active --quiet php${ver}-php-fpm 2>/dev/null && systemctl restart php${ver}-php-fpm
done

echo "✓ SnappyMail Sec-Fetch bypass uygulandı (cross-site navigate artık kabul)"
