#!/bin/sh
# Keep exit playback outside the app process.  The watched D-Bus name remains
# owned while the app is merely minimized, so no sound is played in that case.

set -eu

cover_name_prefix='org.sailfishos.coveraction.harbour.pulleymyfinger.'
sound_file='/usr/share/harbour-pulleymyfinger/qml/sounds/exit.wav'

play_exit_sound() {
    # This separate PulseAudio client outlives sailfish-qml and therefore
    # cannot be cut off by the app's shutdown.
    paplay --client-name=PulleyMyFingerExit "${sound_file}" \
        >/dev/null 2>&1 &
}

while :; do
    active_name=''
    activated_at=0

    dbus-monitor --session \
        "type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged'" \
        2>/dev/null | awk '
            /member=NameOwnerChanged/ { count = 0; next }
            count < 3 && /^[[:space:]]+string / {
                value = $0
                sub(/^[[:space:]]+string "/, "", value)
                sub(/"$/, "", value)
                fields[++count] = value
                if (count == 3) {
                    # A non-whitespace delimiter preserves empty old/new
                    # owner fields when the shell reads this record.
                    print fields[1] "|" fields[2] "|" fields[3]
                    fflush()
                    count = 0
                }
            }
        ' | while IFS='|' read -r name old_owner new_owner; do
            case "${name}" in
                "${cover_name_prefix}"*) ;;
                *) continue ;;
            esac

            if [ -z "${old_owner}" ] && [ -n "${new_owner}" ]; then
                active_name="${name}"
                activated_at=$(date +%s)
            # Sailfish may briefly register and replace a cover action during
            # launch.  Only a stable action is an app-exit signal.
            elif [ "${name}" = "${active_name}" ] \
                    && [ -n "${old_owner}" ] && [ -z "${new_owner}" ] \
                    && [ $(( $(date +%s) - activated_at )) -ge 2 ]; then
                play_exit_sound
                active_name=''
            fi
        done

    # Reconnect if the session bus is restarted.
    sleep 1
done
