#!/bin/bash

if [ -z "$1" ]; then
    echo "Usage: $0 <path-to-flatpak-source-folder>"
    exit 1
fi

SEARCH_DIR="$1"

# Find the file
FILE=$(find "$SEARCH_DIR" -type f \( -name "remote-add.c" -o -name "remoteadd.c" -o -name "flatpak-builtins-remote-add.c" \) | head -n 1)

if [ -z "$FILE" ]; then
    echo "❌ Error: Could not find the remote-add source file in $SEARCH_DIR"
    exit 1
fi

echo "✅ Found file: $FILE"
echo "📋 Creating backup at $FILE.bak"
cp "$FILE" "$FILE.bak"

# Use Python for safe regex replacement
python3 - "$FILE" << 'EOF'
import sys
import re

filepath = sys.argv[1]
with open(filepath, 'r') as f:
    content = f.read()

# Target code block to find:
#   if (opt_authenticator_name && !g_dbus_is_name (opt_authenticator_name))
#     return flatpak_fail (error, _("Invalid authenticator name %s"), opt_authenticator_name);
#
#   if (!flatpak_dir_modify_remote (dir, remote_name, config, gpg_data, cancellable, error))

target_pattern = r'(if \(opt_authenticator_name && !g_dbus_is_name \(opt_authenticator_name\)\)\s+return flatpak_fail \(error, _\("Invalid authenticator name %s"\), opt_authenticator_name\);\s+)(if \(!flatpak_dir_modify_remote)'

def replacer(match):
    indent = "  " # standard indentation here is 2 spaces
    # Inject the bypass logic
    injection = f'{indent}/* Skip GPG key import entirely if GPG verification is disabled */\n{indent}if (opt_no_gpg_verify)\n{indent}  g_clear_pointer (&gpg_data, g_bytes_unref);\n\n{indent}'
    return match.group(1) + injection + match.group(2)

new_content, count = re.subn(target_pattern, replacer, content)

if count > 0:
    with open(filepath, 'w') as f:
        f.write(new_content)
    sys.exit(0)
else:
    sys.exit(1)
EOF

if [ $? -eq 0 ]; then
    echo "🎉 Patch applied successfully to $FILE"
    echo "You can now compile Flatpak to test the fix."
else
    echo "❌ Error: Could not find the exact target string to patch."
    echo "The code may have already been patched, or the source structure has changed."
    mv "$FILE.bak" "$FILE"
    exit 1
fi
