#!/bin/bash
# Adds "Manage in Shelly" right-click action to all Flatpak .desktop files
FLATPAK_DIRS=(
    "/var/lib/flatpak/exports/share/applications"
    "$HOME/.local/share/flatpak/exports/share/applications"
)
LOCAL_APPS_DIR="$HOME/.local/share/applications"
mkdir -p "$LOCAL_APPS_DIR"

for dir in "${FLATPAK_DIRS[@]}"; do
    [ -d "$dir" ] || continue
    for desktop_file in "$dir"/*.desktop; do
        [ -f "$desktop_file" ] || continue
        filename=$(basename "$desktop_file")
        app_id="${filename%.desktop}"
        dest="$LOCAL_APPS_DIR/$filename"

        # Copy if override doesn't exist yet
        [ -f "$dest" ] || cp "$desktop_file" "$dest"

        # Skip if already patched
        grep -q "ShellyManage" "$dest" && continue

        # Add action to existing Actions= line or insert one
        if grep -q "^Actions=" "$dest"; then
            sed -i 's/^Actions=\(.*\)/Actions=\1ShellyManage;/' "$dest"
        else
            sed -i '/^\[Desktop Entry\]/a Actions=ShellyManage;' "$dest"
        fi

        cat >> "$dest" << EOF

[Desktop Action ShellyManage]
Name=Manage in Shelly
Icon=shelly
Exec=/usr/bin/shelly-ui --page flatpak-install
EOF
    done
done

update-desktop-database "$LOCAL_APPS_DIR" 2>/dev/null || true
echo "Flatpak desktop entries patched with Shelly integration."
