summarylogtreecommitdiffstats
path: root/roon-wine
blob: 0910bd312935c93a5c3f343ce49d79e03e91383e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
#!/usr/bin/env bash
set -Eeuo pipefail

readonly APP_NAME=roon-wine
readonly DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}/$APP_NAME"
readonly CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}/$APP_NAME"
readonly CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}/$APP_NAME"
readonly PREFIX="$DATA_HOME/prefix"
readonly CONFIG_FILE="$CONFIG_HOME/config"
readonly INSTALLER_URL='https://download.roonlabs.com/builds/RoonInstaller64.exe'
readonly INSTALLER="$CACHE_HOME/RoonInstaller64.exe"
readonly INSTALLER_SHA512='b93fc7889fef7f4d5dc7e025fcb62815c9a62cbe5e562ab8ea51e2db7bb9901171ccdda42c7ca49206e17b31b38e685dfeb1b4c682e37205f86401d4c6d05add'
readonly PROTON_VERSION='GE-Proton10-34'
readonly PROTON_ARCHIVE="$CACHE_HOME/$PROTON_VERSION.tar.gz"
readonly PROTON_HOME="$DATA_HOME/runtimes"
readonly PROTON_PATH="$PROTON_HOME/$PROTON_VERSION"
readonly PROTON_URL="https://github.com/GloriousEggroll/proton-ge-custom/releases/download/$PROTON_VERSION/$PROTON_VERSION.tar.gz"
readonly PROTON_SHA512='9fd0b2cfbd501c0b5c892239c392c7283a029b5e5d5a77d3f85b0ce190d555456241a18eebca16b53f094b403499201c13550a3f0b9b365e1a5eb5737cbb7303'
readonly BRIDGE_URL='https://download.roonlabs.net/builds/RoonBridge_linuxx64.tar.bz2'
readonly BRIDGE_SHA512='7958ce2d07fb46e5e6b33296e564e2a5c2726acba756fb390144052cd3b13519f62b504db11be1a95b7c2b08354aeffe0aa42cdbc51c6b847e2ffacd9f1d5e70'
readonly BRIDGE_HOME="$DATA_HOME/native-endpoint"
readonly BRIDGE_APP="$BRIDGE_HOME/RoonBridge"
readonly BRIDGE_DATA="$BRIDGE_HOME/data"
readonly BRIDGE_SETTINGS="$BRIDGE_DATA/RAATServer/Settings"
readonly BRIDGE_ARCHIVE="$CACHE_HOME/RoonBridge_linuxx64.tar.bz2"
readonly BRIDGE_SERVICE="$HOME/.config/systemd/user/roonbridge-native.service"
readonly LEGACY_SYSTEM_OUTPUT_LINK="$HOME/.config/systemd/user/default.target.wants/roon-system-output.service"
readonly UMU_140_RUNNER='/usr/lib/roon-proton/roon-umu-run'

display=auto
audio=pipewire
scale=1.0
runner=proton

die() { printf 'roon-wine: %s\n' "$*" >&2; exit 1; }
note() { printf '==> %s\n' "$*"; }
have() { command -v "$1" >/dev/null 2>&1; }
valid_scale() {
  [[ $1 =~ ^[0-9]+([.][0-9]+)?$ ]] || return 1
  awk -v value="$1" 'BEGIN { exit !(value > 0) }'
}

usage() {
  cat <<'EOF'
Usage: roon-wine COMMAND [ARGUMENTS]

Commands:
  setup [MODE]             Install, configure, and launch; MODE: system (default), desktop, direct
  install                  Create/repair the prefix and install Roon
  update                   Install the pinned Roon build without deleting user data
  run                      Launch Roon
  configure                Apply display and audio configuration
  winecfg                  Open Wine configuration for the managed prefix
  doctor                   Print compatibility diagnostics
  set display MODE         MODE: auto, wayland, x11, xwayland
  set audio MODE           MODE: pipewire, pulse, alsa
  set scale FACTOR         Positive decimal UI scale
  set runner RUNNER        RUNNER: proton (default), wine
  runtime                  Install/verify the pinned Proton runtime
  endpoint install         Install the optional direct Linux audio endpoint
  endpoint start|stop      Control the native audio endpoint
  endpoint status          Show native endpoint service status
  endpoint release         Stop playback and release the ALSA device
  endpoint mode desktop    Use Wine System Output through PipeWire
  endpoint mode system     Use native Bridge through the PipeWire default
  endpoint mode direct     Use native Bridge with exclusive/direct ALSA
  kill                     Stop Wine processes in the managed prefix
  help                     Show this help
EOF
}

load_config() {
  [[ -f $CONFIG_FILE ]] || return 0
  while IFS='=' read -r key value; do
    case $key in
      display) [[ $value =~ ^(auto|wayland|x11|xwayland)$ ]] && display=$value ;;
      audio) [[ $value =~ ^(pipewire|pulse|alsa)$ ]] && audio=$value ;;
      scale) valid_scale "$value" && scale=$value ;;
      runner) [[ $value =~ ^(proton|wine)$ ]] && runner=$value ;;
    esac
  done < "$CONFIG_FILE"
}

save_config() {
  mkdir -p "$CONFIG_HOME"
  umask 077
  printf 'display=%s\naudio=%s\nscale=%s\nrunner=%s\n' "$display" "$audio" "$scale" "$runner" > "$CONFIG_FILE"
}

wine_cmd() {
  local overrides='winemenubuilder.exe=d;wminet_utils=d'
  [[ -n ${WINEDLLOVERRIDES:-} ]] && overrides="$WINEDLLOVERRIDES;$overrides"
  env WINEPREFIX="$PREFIX" WINEDLLOVERRIDES="$overrides" "$@"
}

verify_sha512() {
  local file=$1 expected=$2
  [[ -f $file ]] && printf '%s  %s\n' "$expected" "$file" | sha512sum --check --status
}

download_verified() {
  local url=$1 destination=$2 expected=$3 label=$4
  local temporary="$destination.part"
  have curl || die 'curl is required'
  have sha512sum || die 'sha512sum is required'
  if verify_sha512 "$destination" "$expected"; then
    note "using verified cached $label"
    return
  fi
  rm -f -- "$temporary"
  note "downloading pinned $label"
  curl --proto '=https' --proto-redir '=https' --fail --location --retry 3 \
    --output "$temporary" "$url"
  verify_sha512 "$temporary" "$expected" || {
    rm -f -- "$temporary"
    die "$label checksum verification failed; the upstream artifact may have changed"
  }
  mv -f -- "$temporary" "$destination"
}

install_runtime() {
  have umu-run || die 'umu-launcher is required for the Proton runner'
  [[ -x $PROTON_PATH/proton ]] && { note "using $PROTON_VERSION"; return; }
  mkdir -p "$CACHE_HOME" "$PROTON_HOME"
  download_verified "$PROTON_URL" "$PROTON_ARCHIVE" "$PROTON_SHA512" "runtime $PROTON_VERSION"
  rm -rf "$PROTON_PATH"
  tar -xzf "$PROTON_ARCHIVE" -C "$PROTON_HOME"
  [[ -x $PROTON_PATH/proton ]] || die 'Proton runtime extraction failed'
}

proton_cmd() {
  install_runtime
  if [[ -f $PREFIX/version ]]; then
    local prefix_version
    prefix_version=$(<"$PREFIX/version")
    [[ $prefix_version == "$PROTON_VERSION" ]] || die \
      "prefix runtime is $prefix_version, expected $PROTON_VERSION; refusing an unsafe migration"
  fi
  local wayland=0
  [[ $(selected_display) == wayland ]] && wayland=1
  # Wine's wminet_utils implementation is incomplete and can abort current
  # Roon builds. Roon tolerates the optional WMI helper being unavailable.
  local overrides='wminet_utils=d'
  local -a umu=(umu-run)
  [[ -n ${WINEDLLOVERRIDES:-} ]] && overrides="$WINEDLLOVERRIDES;$overrides"
  if umu-run --version 2>&1 | head -n 1 | grep -q 'version 1[.]4[.]0 '; then
    [[ -x $UMU_140_RUNNER ]] || die 'UMU 1.4.0 compatibility runner is missing; reinstall roon-proton'
    umu=("$UMU_140_RUNNER")
  fi
  env WINEPREFIX="$PREFIX" GAMEID=0 PROTONPATH="$PROTON_PATH" \
    PROTON_ENABLE_WAYLAND="$wayland" WINEDLLOVERRIDES="$overrides" "${umu[@]}" "$@"
}

runner_cmd() {
  if [[ $runner == proton ]]; then proton_cmd "$@"; else wine_cmd wine "$@"; fi
}

wine_major() {
  wine --version 2>/dev/null | sed -E 's/^[^0-9]*([0-9]+).*/\1/'
}

wayland_capable() {
  [[ ${XDG_SESSION_TYPE:-} == wayland && -n ${WAYLAND_DISPLAY:-} ]] || return 1
  [[ $runner == proton ]] && return 0
  [[ $(wine_major) =~ ^[0-9]+$ ]] && (( $(wine_major) >= 9 ))
}

selected_display() {
  if [[ $display == auto ]]; then
    # Roon needs a second GL context. GE-Proton 10 renders it reliably through
    # XWayland, while its native Wayland driver fails that context creation.
    if [[ ${XDG_SESSION_TYPE:-} == wayland || -n ${WAYLAND_DISPLAY:-} ]]; then
      if [[ $runner == proton ]]; then printf 'xwayland\n'
      elif wayland_capable; then printf 'wayland\n'; else printf 'xwayland\n'; fi
    else
      printf 'x11\n'
    fi
  else
    printf '%s\n' "$display"
  fi
}

display_available() {
  local selected=$1
  if [[ $selected == wayland ]]; then
    [[ -n ${WAYLAND_DISPLAY:-} ]]
  else
    [[ -n ${DISPLAY:-} ]]
  fi
}

require_display() {
  local selected=$1
  display_available "$selected" && return
  if [[ $selected == wayland ]]; then
    die 'Wayland mode requires WAYLAND_DISPLAY; use display=auto or x11'
  else
    die "$selected mode requires DISPLAY; enable XWayland/X11 or select Wayland"
  fi
}

endpoint_install() {
  require_systemd_user
  have tar || die 'tar is required for the native endpoint'
  mkdir -p "$CACHE_HOME" "$BRIDGE_HOME" "$BRIDGE_DATA" "$(dirname "$BRIDGE_SERVICE")"
  download_verified "$BRIDGE_URL" "$BRIDGE_ARCHIVE" "$BRIDGE_SHA512" 'Roon Bridge archive'
  rm -rf "$BRIDGE_HOME/.install"
  mkdir "$BRIDGE_HOME/.install"
  tar -xjf "$BRIDGE_ARCHIVE" -C "$BRIDGE_HOME/.install"
  [[ -x $BRIDGE_HOME/.install/RoonBridge/start.sh ]] || die 'Roon Bridge extraction failed'
  systemctl --user stop roonbridge-native.service 2>/dev/null || true
  rm -rf "$BRIDGE_APP.old"
  [[ ! -d $BRIDGE_APP ]] || mv "$BRIDGE_APP" "$BRIDGE_APP.old"
  mv "$BRIDGE_HOME/.install/RoonBridge" "$BRIDGE_APP"
  rmdir "$BRIDGE_HOME/.install"
  cat > "$BRIDGE_SERVICE" <<EOF
[Unit]
Description=Roon Bridge native Linux endpoint
After=network-online.target pipewire.service
Wants=network-online.target

[Service]
Environment="ROON_DATAROOT=$BRIDGE_DATA"
Environment="ROON_ID_DIR=$BRIDGE_DATA"
ExecStart="$BRIDGE_APP/start.sh"
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
EOF
  systemctl --user daemon-reload
  systemctl --user disable --now roonbridge-native.service
  note 'native endpoint installed but left disabled'
  note "use 'roon-proton endpoint mode system' for desktop-following audio"
}

require_systemd_user() {
  have systemctl || die 'native endpoint automation requires systemd user services'
  systemctl --user show-environment >/dev/null 2>&1 || \
    die 'no systemd user manager is available; the controller can still run with setup desktop'
}

require_system_output() {
  have python || die 'System Output requires Python'
  [[ -r /usr/lib/alsa-lib/libasound_module_pcm_pipewire.so ]] || \
    die 'System Output requires pipewire-audio; install it and try again'
  systemctl --user start pipewire.socket wireplumber.service >/dev/null 2>&1 || true
  if ! systemctl --user is-active --quiet pipewire.service && \
      ! systemctl --user is-active --quiet pipewire.socket; then
    die 'System Output requires an active PipeWire user service or socket'
  fi
  if ! systemctl --user is-active --quiet wireplumber.service && \
      ! systemctl --user is-active --quiet pipewire-session-manager.service; then
    die 'System Output requires an active WirePlumber user service'
  fi
  [[ -d /sys/module/snd_aloop ]] || \
    die 'snd-aloop is not loaded; reboot or run: sudo modprobe snd-aloop pcm_substreams=1'
}

configure_pipewire_endpoint() {
  python - "$BRIDGE_SETTINGS" <<'PY'
import json
import os
from pathlib import Path
import sys

settings = Path(sys.argv[1])
target = None
config = None
configured = None
configured_path = None

for path in sorted(settings.glob("device_*.json")):
    try:
        candidate = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        continue
    device = candidate.get("output", {}).get("device")
    if device == "hw:CARD=Loopback,DEV=0":
        target = path
        config = candidate
        break
    if (
        device == "plug:pipewire"
        and candidate.get("output", {}).get("name") == "System Output (PipeWire)"
    ):
        configured_path = path
        configured = candidate

if target is None:
    target = configured_path
    config = configured

if target is None or config is None:
    raise SystemExit(1)

config["output"] = {
    "device": "plug:pipewire",
    "type": "alsa",
    "name": "System Output (PipeWire)",
    "dsd_mode": "none",
}
config["volume"] = {"type": "software"}

temporary = target.with_name(f".{target.name}.tmp")
temporary.write_text(
    json.dumps(config, separators=(",", ":")) + "\n",
    encoding="utf-8",
)
os.chmod(temporary, target.stat().st_mode & 0o7777)
os.replace(temporary, target)
PY
}

ensure_pipewire_endpoint() {
  local attempt
  for ((attempt = 0; attempt < 40; attempt++)); do
    if configure_pipewire_endpoint; then return; fi
    sleep 0.25
  done
  die 'Roon Bridge did not create the first Loopback PCM settings; inspect its RAATServer log'
}

pipewire_endpoint_configured() {
  local settings
  for settings in "$BRIDGE_SETTINGS"/device_*.json; do
    [[ -f $settings ]] || continue
    grep -Eq '"device"[[:space:]]*:[[:space:]]*"plug:pipewire"' "$settings" && return
  done
  return 1
}

remove_legacy_system_output() {
  systemctl --user disable --now roon-system-output.service 2>/dev/null || true
  rm -f -- "$LEGACY_SYSTEM_OUTPUT_LINK"
  rm -f -- "$BRIDGE_SERVICE.d/system-output.conf"
  systemctl --user daemon-reload
}

migrate_legacy_system_output() {
  [[ -L $LEGACY_SYSTEM_OUTPUT_LINK ]] || return 0
  note 'migrating the old fixed-rate System Output route to shared PipeWire'
  if (endpoint_command mode system); then return 0; fi
  mkdir -p "$(dirname "$LEGACY_SYSTEM_OUTPUT_LINK")"
  [[ -L $LEGACY_SYSTEM_OUTPUT_LINK ]] || \
    ln -s /usr/lib/systemd/user/roon-system-output.service "$LEGACY_SYSTEM_OUTPUT_LINK"
  printf 'WARN: System Output migration failed; Roon will open and retry on the next launch\n' >&2
}

managed_launcher_pids() {
  local proc pid argument
  for proc in /proc/[0-9]*/cmdline; do
    [[ -r $proc ]] || continue
    pid=${proc#/proc/}
    pid=${pid%/cmdline}
    [[ $pid != "$$" ]] || continue
    while IFS= read -r -d '' argument; do
      if [[ $argument == "$PREFIX"/drive_c/users/*/AppData/Local/Roon/Application/Roon.exe ||
            $argument == "$PREFIX"/drive_c/users/*/AppData/Local/Roon/Application/[0-9]*/Roon.exe ]]; then
        printf '%s\n' "$pid"
        break
      fi
    done < "$proc"
  done
}

stop_managed_prefix() {
  local wineserver='' attempt pid
  local -a launchers=() remaining=()
  mapfile -t launchers < <(managed_launcher_pids)
  ((${#launchers[@]} == 0)) || kill -TERM "${launchers[@]}" 2>/dev/null || true
  if [[ $runner == proton && -x $PROTON_PATH/files/bin/wineserver ]]; then
    wineserver=$PROTON_PATH/files/bin/wineserver
  elif [[ -d $PREFIX ]] && have wineserver; then
    wineserver=$(command -v wineserver)
  fi
  if [[ -n $wineserver ]]; then
    WINEPREFIX="$PREFIX" "$wineserver" -k || true
    WINEPREFIX="$PREFIX" "$wineserver" -w || true
  fi
  for ((attempt = 0; attempt < 20; attempt++)); do
    remaining=()
    for pid in "${launchers[@]}"; do
      kill -0 "$pid" 2>/dev/null && remaining+=("$pid")
    done
    ((${#remaining[@]} == 0)) && return 0
    sleep 0.1
  done
  kill -KILL "${remaining[@]}" 2>/dev/null || true
}

prepare_native_endpoint() {
  # Native Bridge and Roon's Windows local endpoint use the same RAATServer
  # rendezvous. Stop both sides before starting Bridge so it deterministically
  # owns the rendezvous when the controller is launched again.
  systemctl --user stop roonbridge-native.service 2>/dev/null || true
  stop_managed_prefix
}

endpoint_command() {
  require_systemd_user
  case ${1:-status} in
    install) endpoint_install ;;
    start|stop|restart) systemctl --user "$1" roonbridge-native.service ;;
    mode)
      case ${2:-} in
        desktop)
          systemctl --user disable --now roonbridge-native.service roon-system-output.service 2>/dev/null || true
          note 'desktop mode active: relaunch Roon, then enable System Output in Settings > Audio'
          note 'audio will follow the current PipeWire/WirePlumber output'
          ;;
        system)
          [[ -f $BRIDGE_SERVICE ]] || die "native endpoint is not installed; run 'roon-proton endpoint install'"
          require_system_output
          remove_legacy_system_output
          prepare_native_endpoint
          systemctl --user enable --now roonbridge-native.service
          ensure_pipewire_endpoint
          systemctl --user restart roonbridge-native.service
          note 'system-output mode active'
          note 'relaunch Roon so its controller attaches to the native RAAT server'
          note 'in Roon, enable the first Loopback PCM and name it System Output (PipeWire)'
          note 'Roon now plays through PipeWire; leave the second Loopback PCM disabled'
          ;;
        direct)
          [[ -f $BRIDGE_SERVICE ]] || die "native endpoint is not installed; run 'roon-proton endpoint install'"
          remove_legacy_system_output
          prepare_native_endpoint
          systemctl --user enable --now roonbridge-native.service
          note 'exclusive/direct ALSA mode active; relaunch Roon before selecting the direct endpoint'
          ;;
        *) die 'endpoint mode must be desktop, system, or direct' ;;
      esac
      ;;
    release)
      systemctl --user restart roonbridge-native.service
      note 'stopped endpoint playback and released the ALSA device'
      ;;
    status) systemctl --user --no-pager status roonbridge-native.service ;;
    *) die 'endpoint command must be install, start, stop, restart, release, status, or mode' ;;
  esac
}

ensure_roon() {
  find_roon >/dev/null || install_roon
}

setup_roon() {
  local mode=${1:-system}
  case $mode in
    desktop)
      ensure_roon
      if have systemctl && systemctl --user show-environment >/dev/null 2>&1; then
        systemctl --user disable --now roonbridge-native.service roon-system-output.service \
          >/dev/null 2>&1 || true
      fi
      note 'desktop controller mode configured'
      ;;
    system)
      require_systemd_user
      ensure_roon
      require_system_output
      [[ -f $BRIDGE_SERVICE ]] || endpoint_install
      endpoint_command mode system
      ;;
    direct)
      require_systemd_user
      ensure_roon
      [[ -f $BRIDGE_SERVICE ]] || endpoint_install
      endpoint_command mode direct
      ;;
    *) die 'setup mode must be system, desktop, or direct' ;;
  esac
  run_roon
}

alsa_owner() {
  local pcm=${ROON_ALSA_PCM:-} owners card
  if [[ -z $pcm ]]; then
    card=$(awk '$0 ~ /\[Loopback *\]/ { print $1; exit }' /proc/asound/cards 2>/dev/null || true)
    [[ $card =~ ^[0-9]+$ ]] || { printf 'Loopback device not found\n'; return; }
    pcm="/dev/snd/pcmC${card}D0p"
  fi
  [[ -e $pcm ]] || { printf 'device not found\n'; return; }
  owners=$(fuser "$pcm" 2>/dev/null || true)
  if [[ -n $owners ]]; then printf 'in use (pid%s)\n' "$owners"
  else printf 'released\n'
  fi
}

user_service_state() {
  local service state
  for service in "$@"; do
    state=$(systemctl --user is-active "$service" 2>/dev/null || true)
    [[ $state == active ]] && { printf 'active (%s)\n' "$service"; return 0; }
  done
  printf 'inactive or unavailable\n'
  return 1
}

pulse_protocol_state() {
  if have pactl && pactl info >/dev/null 2>&1; then printf 'available\n'
  else printf 'unavailable\n'; return 1; fi
}

configure_prefix() {
  [[ -d $PREFIX ]] || die "prefix does not exist; run 'roon-proton install' first"
  local selected
  selected=$(selected_display)
  if [[ $selected == wayland ]]; then
    wine_cmd wine reg add 'HKEY_CURRENT_USER\Software\Wine\Drivers' \
      /v Graphics /t REG_SZ /d wayland /f >/dev/null
  else
    wine_cmd wine reg delete 'HKEY_CURRENT_USER\Software\Wine\Drivers' \
      /v Graphics /f >/dev/null 2>&1 || true
  fi

  local wine_audio=pulse
  [[ $audio == alsa ]] && wine_audio=alsa
  wine_cmd wine reg add 'HKEY_CURRENT_USER\Software\Wine\Drivers' \
    /v Audio /t REG_SZ /d "$wine_audio" /f >/dev/null
  note "configured display=$selected audio=$audio"
}

open_winecfg() {
  [[ $runner == wine ]] || die "winecfg is only available with 'roon-proton set runner wine'"
  have winecfg || die 'winecfg is required'
  [[ -d $PREFIX ]] || die "prefix does not exist; run 'roon-proton install' first"
  local selected
  selected=$(selected_display)
  note "opening Wine configuration with display=$selected"
  if [[ $selected == wayland ]]; then
    env -u DISPLAY WINEPREFIX="$PREFIX" winecfg
  else
    wine_cmd winecfg
  fi
}

find_roon() {
  local candidate
  candidate=$(find "$PREFIX/drive_c/users" -type f \
    -path '*/AppData/Local/Roon/Application/Roon.exe' \
    -print 2>/dev/null | sort -V | tail -n 1 || true)
  if [[ -z $candidate ]]; then
    candidate=$(find "$PREFIX/drive_c/users" -regextype posix-extended -type f \
      -regex '.*/AppData/Local/Roon/Application/[0-9]+/Roon[.]exe' \
      -print 2>/dev/null | sort -V | tail -n 1 || true)
  fi
  [[ -n $candidate ]] || return 1
  printf '%s\n' "$candidate"
}

activate_proton_payload() {
  local payload=$1 application=$2 build=$3 name
  for name in Roon.exe RAATServer.exe Roon.exe.config RAATServer.exe.config VERSION; do
    [[ -f $payload/$name ]] || die "Roon payload is missing $name"
  done

  for name in Roon RAATServer; do
    python - "$payload/$name.exe" "$application/$name.exe.new" \
      "$build\\$name.dll" <<'PY'
import os
from pathlib import Path
import shutil
import sys

source = Path(sys.argv[1])
destination = Path(sys.argv[2])
replacement = sys.argv[3].encode("ascii")
needle = (source.stem + ".dll").encode("ascii")
data = source.read_bytes()
offset = data.find(needle)
if offset < 0 or data.find(needle, offset + 1) >= 0:
    raise SystemExit(f"could not locate one app-host path in {source.name}")
padding = data[offset + len(needle):offset + len(replacement)]
if any(padding):
    raise SystemExit(f"app-host path is too long for {source.name}")
shutil.copy2(source, destination)
with destination.open("r+b") as output:
    output.seek(offset)
    output.write(replacement)
os.chmod(destination, source.stat().st_mode)
PY
    mv -f -- "$application/$name.exe.new" "$application/$name.exe"
  done

  for name in Roon.exe.config RAATServer.exe.config VERSION; do
    cp --preserve=mode,timestamps -- "$payload/$name" "$application/$name.new"
    mv -f -- "$application/$name.new" "$application/$name"
  done
}

install_proton_payload() {
  have 7z || die '7zip is required to extract the Roon payload'

  # Roon's current 32-bit NSIS bootstrapper crashes in Wine/Proton before its
  # bundled 64-bit controller is installed. Extract the verified upstream
  # payload directly; this is the same $_19_ tree written by the installer.
  local staging payload build destination
  staging=$(mktemp -d "$CACHE_HOME/.roon-payload.XXXXXX") || \
    die 'could not create a temporary payload directory'
  # The dollar sign is the literal NSIS payload directory name.
  # shellcheck disable=SC2016
  if ! 7z x -y "-o$staging" "$INSTALLER" '$_19_/*' >/dev/null; then
    rm -rf -- "$staging"
    die 'failed to extract the Roon controller payload'
  fi
  payload="$staging/\$_19_"
  [[ -f $payload/VERSION && -f $payload/Roon.exe ]] || {
    rm -rf -- "$staging"
    die 'verified Roon installer does not contain the expected controller payload'
  }
  build=$(head -n 1 "$payload/VERSION")
  [[ $build =~ ^[0-9]+$ ]] || {
    rm -rf -- "$staging"
    die 'Roon payload has an invalid build identifier'
  }
  stop_managed_prefix
  destination="$PREFIX/drive_c/users/steamuser/AppData/Local/Roon/Application/$build"
  mkdir -p "$(dirname "$destination")"
  rm -rf -- "$destination.new"
  mv -- "$payload" "$destination.new"
  rm -rf -- "$destination"
  mv -- "$destination.new" "$destination"
  rm -rf -- "$staging"
  activate_proton_payload "$destination" "$(dirname "$destination")" "$build"
  note "installed Roon controller build $build"
}

install_roon() {
  have curl || die 'curl is required'
  mkdir -p "$DATA_HOME" "$CACHE_HOME"
  save_config

  if [[ $runner == wine && ! -d $PREFIX ]]; then
    note 'creating isolated 64-bit Wine prefix'
    env WINEARCH=win64 WINEPREFIX="$PREFIX" wineboot --init
  else
    note 'reusing existing prefix (no user data will be deleted)'
  fi

  if [[ $runner == proton ]]; then
    install_runtime
    if [[ ! -x $PREFIX/drive_c/windows/system32/cmd.exe ]]; then
      note 'initializing the Proton prefix'
      proton_cmd "$PREFIX/drive_c/windows/system32/cmd.exe" /c exit
    fi
  else
    have wine || die 'wine is required for the Wine fallback'
    have winetricks || die 'winetricks is required for the Wine fallback'
    note 'installing required Windows runtime and prefix settings'
    env WINEPREFIX="$PREFIX" winetricks -q win10 dotnet7 nocrashdialog
    configure_prefix
  fi

  download_verified "$INSTALLER_URL" "$INSTALLER" "$INSTALLER_SHA512" 'Roon installer'
  if [[ $runner == proton ]]; then
    install_proton_payload
  else
    local selected
    selected=$(selected_display)
    require_display "$selected"
    if [[ $selected == wayland ]]; then
      (unset DISPLAY; runner_cmd "$INSTALLER")
    else
      runner_cmd "$INSTALLER"
    fi
    find_roon >/dev/null || die 'Roon installation was not detected after the installer closed'
  fi
  note "Roon installation detected at $(find_roon)"
}

run_roon() {
  local exe selected
  exe=$(find_roon) || die "Roon is not installed; run 'roon-proton install'"
  migrate_legacy_system_output
  selected=$(selected_display)
  require_display "$selected"
  [[ $runner == wine ]] && configure_prefix
  note "launching Roon with display=$selected audio=$audio scale=$scale"
  if [[ $selected == wayland ]]; then
    if [[ $runner == proton ]]; then
      (
        unset DISPLAY
        export WINEDEBUG=-all WINEDLLOVERRIDES='windows.media.mediacontrol='
        proton_cmd "$exe" "-scalefactor=$scale"
      )
    else
      env -u DISPLAY WINEPREFIX="$PREFIX" WINEDEBUG=-all \
        WINEDLLOVERRIDES='windows.media.mediacontrol=;winemenubuilder.exe=d;wminet_utils=d' \
        wine "$exe" "-scalefactor=$scale"
    fi
  else
    if [[ $runner == proton ]]; then WINEDEBUG=-all proton_cmd "$exe" "-scalefactor=$scale"
    else wine_cmd env WINEDEBUG=-all wine "$exe" "-scalefactor=$scale"; fi
  fi
}

doctor() {
  load_config
  local failures=0 major='unknown'
  have wine && major=$(wine_major)
  printf '%-20s %s\n' 'session type' "${XDG_SESSION_TYPE:-unknown}"
  printf '%-20s %s\n' 'Wayland display' "${WAYLAND_DISPLAY:-not set}"
  printf '%-20s %s\n' 'X11 display' "${DISPLAY:-not set}"
  printf '%-20s %s\n' 'configured display' "$display -> $(selected_display 2>/dev/null || echo unavailable)"
  printf '%-20s %s\n' 'configured audio' "$audio"
  printf '%-20s %s\n' 'runner' "$runner"
  printf '%-20s %s\n' 'UMU' "$(umu-run --version 2>/dev/null | head -n 1 || echo missing)"
  printf '%-20s %s\n' 'Proton runtime' "$([[ -x $PROTON_PATH/proton ]] && echo "$PROTON_VERSION present" || echo missing)"
  printf '%-20s %s\n' 'Wine' "$(wine --version 2>/dev/null || echo missing)"
  printf '%-20s %s\n' 'PipeWire' "$(user_service_state pipewire.service || true)"
  printf '%-20s %s\n' 'Pulse service' "$(user_service_state pipewire-pulse.service pulseaudio.service || true)"
  printf '%-20s %s\n' 'Pulse protocol' "$(pulse_protocol_state || true)"
  printf '%-20s %s\n' 'prefix' "$([[ -d $PREFIX ]] && echo present || echo missing)"
  printf '%-20s %s\n' 'Roon executable' "$(find_roon >/dev/null && echo present || echo missing)"
  printf '%-20s %s\n' 'native endpoint' "$(systemctl --user is-active roonbridge-native.service 2>/dev/null || echo inactive)"
  if systemctl --user is-active --quiet roonbridge-native.service 2>/dev/null && \
      pipewire_endpoint_configured; then
    printf '%-20s %s\n' 'endpoint mode' 'System Output via shared PipeWire device'
  elif systemctl --user is-active --quiet roonbridge-native.service 2>/dev/null; then
    printf '%-20s %s\n' 'endpoint mode' 'exclusive/direct ALSA'
  else
    printf '%-20s %s\n' 'endpoint mode' 'desktop System Output -> PipeWire'
  fi
  printf '%-20s %s\n' 'ALSA device' "$(alsa_owner)"

  if [[ $runner == proton ]]; then
    have umu-run || { printf 'WARN: umu-launcher is not installed\n' >&2; failures=1; }
  else
    have wine || { printf 'WARN: wine is not installed\n' >&2; failures=1; }
  fi
  if ! display_available "$(selected_display)"; then
    printf 'WARN: selected display backend is unavailable in this session\n' >&2
    failures=1
  fi
  if [[ $runner == wine && $major == 11 ]]; then
    printf 'WARN: Wine 11 has a reported washed-out color regression with Roon\n' >&2
  fi
  if [[ $audio != alsa ]] && ! pulse_protocol_state >/dev/null; then
    printf 'WARN: no Pulse-compatible audio server is reachable; the local Roon output may be unavailable\n' >&2
    failures=1
  fi
  return "$failures"
}

set_value() {
  local key=${1:-} value=${2:-}
  case $key in
    display) [[ $value =~ ^(auto|wayland|x11|xwayland)$ ]] || die 'display must be auto, wayland, x11, or xwayland'; display=$value ;;
    audio) [[ $value =~ ^(pipewire|pulse|alsa)$ ]] || die 'audio must be pipewire, pulse, or alsa'; audio=$value ;;
    scale) valid_scale "$value" || die 'scale must be a positive decimal'; scale=$value ;;
    runner) [[ $value =~ ^(proton|wine)$ ]] || die 'runner must be proton or wine'; runner=$value ;;
    *) die 'setting must be display, audio, scale, or runner' ;;
  esac
  save_config
  note "saved $key=$value"
}

main() {
  load_config
  case ${1:-help} in
    setup) setup_roon "${2:-system}" ;;
    install|update) install_roon ;;
    run) run_roon ;;
    configure) configure_prefix ;;
    winecfg) open_winecfg ;;
    runtime) install_runtime ;;
    endpoint) endpoint_command "${2:-status}" "${3:-}" ;;
    doctor) doctor ;;
    set) shift; set_value "${1:-}" "${2:-}" ;;
    kill) stop_managed_prefix ;;
    help|-h|--help) usage ;;
    *) usage >&2; exit 2 ;;
  esac
}

if [[ ${ROON_PROTON_LIB_ONLY:-0} != 1 ]]; then
  main "$@"
fi