#!/bin/sh
# Apply the XFCE settings required by the legacy PVR DDX after login.
set -u

PATH=/usr/local/bin:/usr/bin:/bin
export PATH

# xfconfd can appear slightly after XDG autostart processing.
attempt=0
while [ "$attempt" -lt 20 ]; do
    if xfconf-query -c xfwm4 -p /general/use_compositing -s false \
            >/dev/null 2>&1; then
        break
    fi
    if xfconf-query -c xfwm4 -p /general/use_compositing \
            -n -t bool -s false >/dev/null 2>&1; then
        break
    fi
    attempt=$((attempt + 1))
    sleep 1
done

# A presentation image should not blank the HDMI output during a demo.
if command -v xset >/dev/null 2>&1; then
    xset s off >/dev/null 2>&1 || true
    xset -dpms >/dev/null 2>&1 || true
fi

# Keep English as the initial layout, add Russian, and use Alt+Shift for group
# switching. xfsettingsd consumes these properties on every XFCE login; the
# direct XKB call makes the first session deterministic as well.
xfconf_set() {
    channel=$1
    property=$2
    type=$3
    value=$4
    if xfconf-query -c "$channel" -p "$property" >/dev/null 2>&1; then
        xfconf-query -c "$channel" -p "$property" -s "$value" \
            >/dev/null 2>&1 || true
    else
        xfconf-query -c "$channel" -p "$property" -n -t "$type" -s "$value" \
            >/dev/null 2>&1 || true
    fi
}
xfconf_set keyboard-layout /Default/XkbDisable bool false
xfconf_set keyboard-layout /Default/XkbModel string pc105
xfconf_set keyboard-layout /Default/XkbLayout string 'us,ru'
xfconf_set keyboard-layout /Default/XkbVariant string ','
xfconf_set keyboard-layout /Default/XkbOptions/Group string 'grp:alt_shift_toggle'
if command -v setxkbmap >/dev/null 2>&1; then
    setxkbmap -model pc105 -layout 'us,ru' -variant ',' \
        -option '' -option 'grp:alt_shift_toggle' >/dev/null 2>&1 || true
fi

# Prefer HDMI when it is connected, while leaving analog as the fallback.
if command -v mcom03-audioctl >/dev/null 2>&1; then
    mcom03-audioctl auto >/dev/null 2>&1 || true
fi
if command -v wpctl >/dev/null 2>&1; then
    # Avoid digital clipping: the clean profile inherited HDMI gain above
    # 100%, which is audible as crackling on high-level AAC tracks.
    wpctl set-volume @DEFAULT_AUDIO_SINK@ "${MCOM03_SINK_VOLUME:-1.0}" >/dev/null 2>&1 || true
fi

# Add the volume applet once. `xfce4-panel --add` opens an interactive dialog
# and may remain attached when this helper runs through SSH, so update the
# panel's integer array directly and reload the already running panel.
if command -v xfce4-panel >/dev/null 2>&1 && \
        ! xfconf-query -c xfce4-panel -lv 2>/dev/null | \
            grep -Eq '/plugins/plugin-[0-9]+[[:space:]]+pulseaudio$'; then
    panel_property=/panels/panel-1/plugin-ids
    panel_ids=$(xfconf-query -c xfce4-panel -p "$panel_property" 2>/dev/null | \
        sed -n '/^[0-9][0-9]*$/p')
    next_id=$(xfconf-query -c xfce4-panel -lv 2>/dev/null | \
        sed -n 's#^/plugins/plugin-\([0-9][0-9]*\)[[:space:]].*#\1#p' | \
        sort -n | tail -1)
    if [ -n "$panel_ids" ] && [ -n "$next_id" ]; then
        next_id=$((next_id + 1))
        # Build one `-t int -s VALUE` pair per existing array element.
        set --
        for panel_id in $panel_ids "$next_id"; do
            set -- "$@" -t int -s "$panel_id"
        done
        if xfconf-query -c xfce4-panel -p "$panel_property" -a "$@" \
                >/dev/null 2>&1 && \
                xfconf-query -c xfce4-panel \
                    -p "/plugins/plugin-$next_id" -n -t string \
                    -s pulseaudio >/dev/null 2>&1; then
            xfce4-panel --restart >/dev/null 2>&1 || true
        fi
    fi
fi

# The panel must use the same app-scoped GTK renderer as the audio menu entries.
# Keep an explicitly selected alternative mixer.
if command -v mcom03-audio-settings >/dev/null 2>&1; then
    audio_plugins=$(xfconf-query -c xfce4-panel -lv 2>/dev/null | \
        sed -n 's#^\(/plugins/plugin-[0-9][0-9]*\)[[:space:]][[:space:]]*pulseaudio$#\1#p')
    for audio_plugin in $audio_plugins; do
        mixer_command=$(xfconf-query -c xfce4-panel \
            -p "$audio_plugin/mixer-command" 2>/dev/null || true)
        case "$mixer_command" in
            ''|pavucontrol|/usr/bin/pavucontrol)
                xfconf_set xfce4-panel "$audio_plugin/mixer-command" \
                    string mcom03-audio-settings
                ;;
        esac
    done
fi

# The accepted desktop uses the adaptive PVR Picom build, while XFWM's own
# compositor remains disabled. Configure this once and keep the user service
# enabled on subsequent logins.
PICOM_MODE_OVERRIDE="$HOME/.config/systemd/user/mcom03-picom.service.d/10-mcom03-mode.conf"
if command -v mcom03-picom-control >/dev/null 2>&1; then
    if ! grep -Fxq 'Environment=MCOM03_PICOM_MODE=adaptive-hwcursor' \
            "$PICOM_MODE_OVERRIDE" 2>/dev/null; then
        mcom03-picom-control mode adaptive-hwcursor >/dev/null 2>&1 || true
    fi
    mcom03-picom-control enable >/dev/null 2>&1 || true
fi

if command -v xdg-settings >/dev/null 2>&1 &&
        [ -r /usr/local/share/applications/chromium.desktop ]; then
    xdg-settings set default-web-browser chromium.desktop >/dev/null 2>&1 || true
fi
if command -v xdg-mime >/dev/null 2>&1 &&
        [ -r /usr/local/share/applications/chromium.desktop ]; then
    for mime in text/html x-scheme-handler/http x-scheme-handler/https; do
        xdg-mime default chromium.desktop "$mime" >/dev/null 2>&1 || true
    done
fi

# XFCE's generic "Web Browser" menu entry goes through Exo rather than the
# MIME default. Point it at the desktop-facing MCom03 launcher explicitly;
# the stock Chromium helper resolves /usr/bin/chromium and bypasses PVR setup.
if [ -r /usr/local/share/xfce4/helpers/mcom03-chromium.desktop ]; then
    HELPER_DIR="$HOME/.config/xfce4"
    HELPER_RC="$HELPER_DIR/helpers.rc"
    mkdir -p "$HELPER_DIR"
    if grep -q '^WebBrowser=' "$HELPER_RC" 2>/dev/null; then
        sed -i 's/^WebBrowser=.*/WebBrowser=mcom03-chromium/' "$HELPER_RC"
    else
        printf '%s\n' 'WebBrowser=mcom03-chromium' >>"$HELPER_RC"
    fi
fi

exit 0
