#!/bin/bash
# Rebuild the renamed menu entries.
#
# Rather than editing the files KDE's packages own — which dpkg would revert on
# every upgrade, and which makes "dpkg -V" report a tampered system — this
# copies each entry into a directory that comes first in XDG_DATA_DIRS and
# changes only the Name lines. A desktop entry is identified by its filename,
# so the copy shadows the original wherever entries are looked up: the menu,
# KRunner, the task manager, "open with".
#
# Re-run by a dpkg trigger whenever anything touches /usr/share/applications,
# so an upstream upgrade that ships a new version of an entry is picked up
# rather than leaving a stale copy in front of it.
set -euo pipefail

CONFIG=/usr/share/motel/app-names/renames.conf
HIDDEN=/usr/share/motel/app-names/hidden.conf
SOURCE_DIR=/usr/share/applications
TARGET_DIR=/usr/share/motel/xdg/applications

[ -f "$CONFIG" ] || exit 0

install -d "$TARGET_DIR"

# Anything we generated before is rebuilt from scratch: an entry dropped from
# the configuration must stop being overridden, and a stale copy of an entry
# whose application has been removed would leave a dead item in the menu.
find "$TARGET_DIR" -maxdepth 1 -name '*.desktop' -delete

renamed=0
while IFS='|' read -r id name name_ar; do
    case "$id" in ''|\#*) continue ;; esac
    [ -n "$name" ] || continue

    source_file="$SOURCE_DIR/$id"
    # Not an error: the configuration covers applications that some editions
    # do not install.
    [ -f "$source_file" ] || continue

    target_file="$TARGET_DIR/$id"

    # Rewrite the Name lines in the [Desktop Entry] group, and only there.
    #
    # The group check is not decoration. A .desktop file also carries
    # [Desktop Action ...] groups — the jump list you get from right-clicking
    # a task-bar icon, "Open a New Window" and friends — and those have Name
    # lines of their own. Stripping those as well leaves the actions nameless,
    # which is how a rename turns into a visibly broken context menu.
    #
    # The localised names go too: leaving Name[ar] alone would rename the
    # application in English and leave it as "Dolphin" for every Arabic user,
    # which is worse than not renaming it at all. Other languages fall back to
    # our English name, which is the behaviour we want in a distribution that
    # ships English and Arabic.
    awk -v name="$name" -v name_ar="$name_ar" '
        /^\[/ { group = $0 }

        # Emit ours immediately after the header, so they land in the entry
        # group no matter where the original kept its own Name line.
        /^\[Desktop Entry\][[:space:]]*$/ {
            print
            print "Name=" name
            if (name_ar != "") print "Name[ar]=" name_ar
            next
        }

        group == "[Desktop Entry]" && /^Name(\[[^]]*\])?[[:space:]]*=/ { next }

        { print }
    ' "$source_file" > "$target_file"

    chmod 0644 "$target_file"
    renamed=$((renamed + 1))
done < "$CONFIG"

hidden=0
if [ -f "$HIDDEN" ]; then
    while read -r id; do
        case "$id" in ''|\#*) continue ;; esac
        [ -f "$SOURCE_DIR/$id" ] || continue

        # A complete entry rather than a stub: some launchers ignore a file
        # that is only [Desktop Entry] + Hidden, and a malformed entry can
        # make a menu rebuild noisy. Copying the original and adding the key
        # keeps it valid whatever reads it.
        {
            awk '!/^(Hidden|NoDisplay)[[:space:]]*=/' "$SOURCE_DIR/$id"
            echo "Hidden=true"
            echo "NoDisplay=true"
        } > "$TARGET_DIR/$id"
        chmod 0644 "$TARGET_DIR/$id"
        hidden=$((hidden + 1))
    done < "$HIDDEN"
fi

echo "motel: renamed $renamed application entries, hid $hidden"

# Without this the menu can take minutes to notice, and the user concludes the
# upgrade broke something.
if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$TARGET_DIR" 2>/dev/null || true
fi
