#!/bin/bash
SLUG=$1

if pactl list sources short | grep -q AT2040; then
    AUDIO_OUT="alsa_output.usb-AT_AT2040USB_202011110001-00.analog-stereo"
else
    AUDIO_OUT="alsa_output.pci-0000_00_1f.3.analog-stereo"
fi

current_desktop=$(xprop -root _NET_CURRENT_DESKTOP | awk '{print $3}')

SINK_NAME="output-$SLUG"
if ! pactl list sinks short | grep -q "$SINK_NAME"; then
    pactl load-module module-null-sink \
        sink_name="$SINK_NAME" \
        sink_properties="device.description=$SINK_NAME node.always-process=true node.autoconnect=false"
    pw-link "${SINK_NAME}:monitor_FL" "${AUDIO_OUT}:playback_FL" 2>/dev/null
    pw-link "${SINK_NAME}:monitor_FR" "${AUDIO_OUT}:playback_FR" 2>/dev/null
fi

# Pan based on workspace 4-12: ws4=30%L/0%R, ws8=15%L/15%R, ws12=0%L/30%R
WS=$current_desktop
if [ "$WS" -lt 4 ]; then WS=4; fi
if [ "$WS" -gt 12 ]; then WS=12; fi
LEFT_VOL=$(( (30 * (12 - WS) + 4) / 8 ))
RIGHT_VOL=$(( (30 * (WS - 4) + 4) / 8 ))
pactl set-sink-volume "$SINK_NAME" "${LEFT_VOL}%" "${RIGHT_VOL}%"

# Store workspace->slug mapping and panned volumes for bbb-focus
echo "$SLUG" > "/tmp/bbb-ws-${current_desktop}"
echo "${LEFT_VOL}% ${RIGHT_VOL}%" > "/tmp/bbb-vol-${SLUG}"

firefox -new-window https://media.emacsconf.org/2026/backstage/assets/redirects/open/bbb-$SLUG.html &
sleep 0.5
xdotool search --onlyvisible --class "firefox" | while read -r wid; do
		win_desktop=$(xprop -id "$wid" _NET_WM_DESKTOP | awk '{print $3}')
		if [ "$win_desktop" = "$current_desktop" ]; then
        xprop -id "$wid" -f WM_CLASS 8s -set WM_CLASS "bbb-$SLUG"
        break
    fi
done

firefox -new-window https://pad.emacsconf.org/2026-$SLUG &
sleep 0.5
xdotool search --onlyvisible --class "firefox" | while read -r wid; do
		win_desktop=$(xprop -id "$wid" _NET_WM_DESKTOP | awk '{print $3}')
		if [ "$win_desktop" = "$current_desktop" ]; then
        xprop -id "$wid" -f WM_CLASS 8s -set WM_CLASS "pad-$SLUG"
        break
    fi
done

emacsclient -c -e "(switch-to-buffer \"transcript-$SLUG\")" -e
sleep 0.5
xdotool search --onlyvisible --class "emacs" | while read -r wid; do
		win_desktop=$(xprop -id "$wid" _NET_WM_DESKTOP | awk '{print $3}')
		if [ "$win_desktop" = "$current_desktop" ]; then
        xprop -id "$wid" -f WM_CLASS 8s -set WM_CLASS "emacs-$SLUG"
        break
    fi
done

SCREEN_WIDTH=$(xdotool getdisplaygeometry | awk '{print $1}')
SCREEN_HEIGHT=$(xdotool getdisplaygeometry | awk '{print $2}')

HALF_WIDTH=$((SCREEN_WIDTH / 2))
HALF_HEIGHT=$((SCREEN_HEIGHT / 2))

wmctrl -x -r "bbb-$SLUG" -b remove,maximized_vert,maximized_horz
wmctrl -x -r "bbb-$SLUG" -e 0,0,0,$HALF_WIDTH,$SCREEN_HEIGHT
Remind me tomorrow to check if my PVP setup scripts are alright and to work on the audio part.
wmctrl -x -r "pad-$SLUG" -b remove,maximized_vert,maximized_horz
wmctrl -x -r "pad-$SLUG" -e 0,$HALF_WIDTH,0,$HALF_WIDTH,$HALF_HEIGHT

wmctrl -x -r "emacs-$SLUG" -b remove,maximized_vert,maximized_horz
wmctrl -x -r "emacs-$SLUG" -e $0,$HALF_WIDTH,$HALF_HEIGHT,$HALF_WIDTH,$HALF_HEIGHT
