#!/bin/bash
# reset-ui: brings back the desktop's top bar, its background and its window
# manager inside the running session, without closing the apps that are open.
# The viewer's Reset desktop UI button runs it through
# POST /api/desktop/reset-ui.
#
# The top bar goes back to XFCE's default layout. The old layout is kept as
# xfce4-panel.xml.before-reset beside the bar's settings, so a broken one can
# be looked at and the user's own items recovered by hand. Restart desktop
# keeps the layout, and starts the programs the session last saved, with the
# top bar put back in a save that lacks it (addBarToSavedSession).
#
# With --bar it starts only the top bar again, keeping its layout and leaving
# the background and the window manager alone. The app runs it so for a bar
# that xfce4-session dropped from the session (sessionbus.go): the bar is
# fine, but outside the session, so the session's saves leave it out.
#
# The programs started here get the session's own environment, which holds
# more than the app's (the Applications menu's XDG_* and the formats
# libexec/session sets), and write to the session's log like the rest of it.
#
# Exit codes are read by devgrail-desktop (api.go): 2 for an argument it does
# not know, 3 when the session is not running, 4 when the top bar does not come
# back.
#
# The app stops a helper after 30 seconds (helperTimeout in localapi.go), which
# would leave the bar stopped halfway, so every wait here is bounded and the
# script ends within about 28 seconds whatever hangs.
set -euo pipefail

bar_only=0
case "${1:-}" in
    '') ;;
    --bar) bar_only=1 ;;
    *) echo 'usage: reset-ui [--bar]' >&2; exit 2 ;;
esac

# ask <program> [args...] asks a running program something over D-Bus. A hung
# program never answers, and D-Bus waits 25 seconds before giving up.
ask() {
    timeout 2 "$@" >/dev/null 2>&1 || true
}

: "${DISPLAY:?the app sets DISPLAY}"
uid="$(id -u)"

not_running() {
    echo 'the desktop session is not running' >&2
    exit 3
}

# running <name> says whether a process of that name runs. A zombie does not:
# in a container whose first process does not reap orphans, an xfconfd that
# exited stays one, and pgrep still lists it.
running() {
    local pid stat
    for pid in $(pgrep -u "$uid" -x "$1" || true); do
        stat="$(cat "/proc/$pid/stat" 2>/dev/null)" || continue
        stat="${stat##*) }"
        [ "${stat%% *}" = Z ] || return 0
    done
    return 1
}

# wait_gone <seconds> <name> waits for every process of that name to exit.
wait_gone() {
    local tries=$(($1 * 10))
    while [ "$tries" -gt 0 ] && running "$2"; do
        sleep 0.1
        tries=$((tries - 1))
    done
    ! running "$2"
}

# environ_of <pid> fills the array env with the process's environment.
environ_of() {
    env=()
    mapfile -d '' -t env <"/proc/$1/environ" 2>/dev/null || return 1
    [ ${#env[@]} -gt 0 ]
}

# value_of <name> prints a variable's value from env.
value_of() {
    local kv
    for kv in "${env[@]}"; do
        if [ "${kv%%=*}" = "$1" ]; then
            printf '%s' "${kv#*=}"
            return 0
        fi
    done
    return 1
}

# --- the running session -------------------------------------------------------

# This display's session: a workspace runs one, but its display says which.
session=''
for pid in $(pgrep -u "$uid" -x xfce4-session || true); do
    if environ_of "$pid" && [ "$(value_of DISPLAY || true)" = "$DISPLAY" ]; then
        session="$pid"
        break
    fi
done
[ -n "$session" ] || not_running
environ_of "$session" || not_running
session_env=("${env[@]}")
bus="$(value_of DBUS_SESSION_BUS_ADDRESS || true)"
[ -n "$bus" ] || not_running
export DBUS_SESSION_BUS_ADDRESS="$bus"
config_home="$(value_of XDG_CONFIG_HOME || true)"
config_home="${config_home:-$HOME/.config}"

# xfce4-session sets SESSION_MANAGER for its children only, after its own
# environment was made, so it is read from one of them: xfsettingsd first,
# which this leaves alone. A program started without it is not part of the
# session and would not be saved with it.
socket="/tmp/.ICE-unix/$session"
[ -S "$socket" ] || not_running
session_manager=''
for name in xfsettingsd xfwm4 xfdesktop xfce4-panel; do
    for pid in $(pgrep -u "$uid" -P "$session" -x "$name" || true); do
        if environ_of "$pid"; then
            value="$(value_of SESSION_MANAGER || true)"
            if [[ $value == *"$socket" ]]; then
                session_manager="$value"
                break 2
            fi
        fi
    done
done
if [ -z "$session_manager" ]; then
    host="$(hostname)"
    session_manager="local/$host:@$socket,unix/$host:$socket"
fi

# The session's environment, for the programs started below.
start_env=()
for kv in "${session_env[@]}"; do
    [ "${kv%%=*}" = SESSION_MANAGER ] || start_env+=("$kv")
done
start_env+=("SESSION_MANAGER=$session_manager")

# start <program> [args...] starts a program inside the session, detached from
# this script, with its output in the session's log: xfce4-session's own
# output is the app's pipe to xfce.log. The helper runner reads this script's
# output until it closes, so the program must not hold it.
start() {
    setsid -f env -i "${start_env[@]}" "$@" </dev/null >>"/proc/$session/fd/1" 2>&1
}

has_owner() {
    dbus-send --session --print-reply=literal --reply-timeout=2000 --dest=org.freedesktop.DBus \
        /org/freedesktop/DBus org.freedesktop.DBus.NameHasOwner "string:$1" 2>/dev/null |
        grep -q true
}

# --- the top bar -------------------------------------------------------------

# stop_panel stops the top bar. Asked to quit, it tells xfce4-session not to
# start it again. One that does not answer is killed, and fails.
stop_panel() {
    ask xfce4-panel --quit
    wait_gone 2 xfce4-panel && return 0
    pkill -u "$uid" -x xfce4-panel || true
    if ! wait_gone 1 xfce4-panel; then
        pkill -KILL -u "$uid" -x xfce4-panel || true
        wait_gone 1 xfce4-panel || true
    fi
    return 1
}

# wait_bar <also> waits, until the script's time is nearly up, for the top bar
# to hold its name and for the command <also> to succeed. While no bar runs and
# none holds the name, one is started: the bus lets go of a stopped bar's name
# a moment after it exits, and a bar started before then hands over to the old
# one and exits, leaving none. One already starting is left to finish.
wait_bar() {
    while [ "$SECONDS" -lt 25 ]; do
        if has_owner org.xfce.Panel; then
            "$@" && return 0
        elif ! running xfce4-panel; then
            start xfce4-panel
        fi
        sleep 0.5
    done
    return 1
}

# With --bar, the bar is stopped and started again in the session, with the
# layout it had. One outside the session is not started again by
# xfce4-session, however it stopped. The old one's name is waited out, so that
# it is not taken for the new one; one that still has the name after that was
# started meanwhile, and is kept.
if [ "$bar_only" = 1 ]; then
    if running xfce4-panel; then
        stop_panel || true
        for _ in $(seq 1 10); do
            has_owner org.xfce.Panel || break
            sleep 0.2
        done
    fi
    wait_bar true && exit 0
    echo 'the top bar did not start' >&2
    exit 4
fi

# xfce4-session starts a killed bar again at once. That one would read the old
# layout, and keep starting xfconfd again while the layout is replaced, so it
# is asked to quit too; it answers, being new.
if running xfce4-panel && ! stop_panel; then
    for _ in $(seq 1 20); do
        has_owner org.xfce.Panel && break
        sleep 0.1
    done
    if running xfce4-panel; then
        stop_panel || true
    fi
fi

# --- the top bar's layout ------------------------------------------------------

# An empty channel would have the bar ask, in a dialog, which layout to start
# with, so the default layout is put in place directly. xfconfd writes its
# channels to disk as it quits, so it goes first; D-Bus starts it again on the
# next request, and the programs that use it reach it by its bus name.
#
# stop_xfconfd <seconds> stops it, giving it that long to write its channels.
stop_xfconfd() {
    pkill -u "$uid" -x xfconfd || true
    if ! wait_gone "$1" xfconfd; then
        pkill -KILL -u "$uid" -x xfconfd || true
        wait_gone 1 xfconfd || true
    fi
}
stop_xfconfd 3
channels="$config_home/xfce4/xfconf/xfce-perchannel-xml"
mkdir -p "$channels"
if [ -f "$channels/xfce4-panel.xml" ]; then
    cp -f "$channels/xfce4-panel.xml" "$channels/xfce4-panel.xml.before-reset"
fi
cp -f /etc/xdg/xfce4/panel/default.xml "$channels/xfce4-panel.xml.tmp"
# Something may have started it again meanwhile: a bar xfce4-session started
# again, or a browser sending its settings. That one read the old layout, and
# would hand it to the bar, or write it back over the default as it quits.
if running xfconfd; then
    stop_xfconfd 1
fi
mv -f "$channels/xfce4-panel.xml.tmp" "$channels/xfce4-panel.xml"

# --- the session's programs ----------------------------------------------------

if has_owner org.xfce.Panel; then
    # xfce4-session started a killed one again after all: it read the old
    # layout.
    ask xfce4-panel --restart
else
    start xfce4-panel
fi

# A new one finding the old one's name still taken would only hand over to it
# and exit, so the old one is waited for.
if running xfdesktop; then
    ask xfdesktop --quit
    if ! wait_gone 2 xfdesktop; then
        pkill -KILL -u "$uid" -x xfdesktop || true
        wait_gone 1 xfdesktop || true
    fi
fi
start xfdesktop

# A running window manager is left alone: it is saved to be started again at
# once, so replacing it could have xfce4-session start it again to fight the
# new one.
if ! running xfwm4; then
    start xfwm4
fi

# Both are waited for, so the caller finds them on the bus; only a top bar
# that does not come back fails the reset. The wait ends in time for the
# app's limit, however long the steps above took.
wait_bar has_owner org.xfce.xfdesktop && exit 0
has_owner org.xfce.Panel && exit 0
echo 'the top bar did not start' >&2
exit 4
