#!/bin/sh

###
# This script applies the default x-terminal-emulator configuration,
# which is system-wide, to xdg-terminal-exec which is per-user and
# uses .desktop files instead.
#
# We will avoid overwriting an existing xdg-terminal-exec configuration.
###

set -uf

XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
XDG_DATA_DIRS="${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
LOWERCASE_XDG_CURRENT_DESKTOP=$(printf '%s' "${XDG_CURRENT_DESKTOP-}" | tr '[:upper:]' '[:lower:]')
IFS=":"

for desktop in ${LOWERCASE_XDG_CURRENT_DESKTOP}; do
    CONFIGS=${CONFIGS:+${CONFIGS}${IFS}}${XDG_CONFIG_HOME%/}/${desktop}-xdg-terminals.list
done
CONFIGS=${CONFIGS:+${CONFIGS}${IFS}}${XDG_CONFIG_HOME%/}/xdg-terminals.list

# gnome-terminal used to set itself as the user-default terminal on app launch
# even if a system-wide default already existed. Undo this configuration.
for config in ${CONFIGS}; do
    if [ -f "$config" ]; then
        current=$(sed -n '/^\s*#/!{p;q}' "$config")
        if [ "$current" = "org.gnome.Terminal.desktop" ]; then
            rm "$config"
        fi
    fi
done

# If there is an existing valid configuration, bail out.
for config in ${CONFIGS}; do
    if [ -f "$config" ]; then
        exit 0
    fi
done

# If the user never changed the x-terminal-emulator configuration, bail out.
if ! update-alternatives --query x-terminal-emulator | grep -q "^Status: manual"; then
    exit 0
fi

TERMINAL_EXEC="$(realpath "$(which x-terminal-emulator)")"
if [ ! -x "$TERMINAL_EXEC" ]; then
    exit 0
fi

# Find a matching desktop file entry
for dir in ${XDG_DATA_HOME}${IFS}${XDG_DATA_DIRS}; do
    APPLICATIONS_DIRS=${dir%/}/applications/${APPLICATIONS_DIRS:+${IFS}${APPLICATIONS_DIRS}}
done

# shellcheck disable=SC2086 # intentional word splitting
TERMINAL_DESKTOP="$(find $APPLICATIONS_DIRS -type f -name '*.desktop' -exec sh -c \
    'sed -n "/\[Desktop Entry\]/,/\[.*\]/p" "$1" | grep -q -E "^Exec=$2|^Exec=$(basename "$2")" && echo "$1"' sh {} "$TERMINAL_EXEC" \; \
    2>/dev/null | head -n1)"
if [ ! -f "$TERMINAL_DESKTOP" ]; then
    exit 0
fi

TERMINAL_DESKTOP=$(basename "$TERMINAL_DESKTOP")
# The default terminal might be more expressive than just a desktkop file id,
# because it supports specifying a desktop action name.
# If the current default matches or is a specific action of the same terminal, bail out.
case "$(xdg-terminal-exec --print-id)" in
    "${TERMINAL_DESKTOP}") exit 0;;
    "${TERMINAL_DESKTOP}:"*) exit 0;;
esac

# shellcheck disable=SC2086 # intentional word splitting
set -- $LOWERCASE_XDG_CURRENT_DESKTOP
TERMINALS_LIST_FILE="${XDG_CONFIG_HOME%/}/${1-}${1:+-}xdg-terminals.list"
echo "$TERMINAL_DESKTOP" > "${TERMINALS_LIST_FILE}"
