#!/usr/bin/env bash # Sway analog of sunshine-prestart.sh. Runs as ExecStartPre for sunshine.service # on Ubuntu/Debian installs that use the Sway-headless path. # # Two jobs: # 1. Confirm sway is reachable; create HEADLESS-1 if it doesn't exist yet. # 2. Sync sunshine.conf's `output_name` to whatever the headless output is # currently named (`create_output` may auto-assign HEADLESS-2, -3, etc. # after a session restart). set -uo pipefail log() { printf '[sunshine-prestart-sway] %s\n' "$*" >&2; } CONF="$HOME/.config/sunshine/sunshine.conf" if [[ -z "${SWAYSOCK:-}" ]]; then for sock in "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"/sway-ipc.*.sock; do [[ -S "$sock" ]] || continue export SWAYSOCK="$sock" break done fi if [[ -z "${SWAYSOCK:-}" ]]; then log "sway not running; nothing to prepare." exit 0 fi if ! command -v swaymsg >/dev/null 2>&1 || ! command -v jq >/dev/null 2>&1; then log "swaymsg/jq missing; skipping prestart." exit 0 fi # Reduce to exactly one HEADLESS-* output. mapfile -t headless_outputs < <(swaymsg -t get_outputs -r 2>/dev/null \ | jq -r '.[].name | select(startswith("HEADLESS-"))' \ | sort -V) existing="${headless_outputs[0]:-}" if [[ -z "$existing" ]]; then log "No headless output present; creating one" swaymsg create_output HEADLESS-1 >/dev/null 2>&1 || swaymsg create_output >/dev/null 2>&1 || true for _ in 1 2 3 4 5; do existing="$(swaymsg -t get_outputs -r 2>/dev/null \ | jq -r '.[].name | select(startswith("HEADLESS-"))' \ | sort -V | head -1)" [[ -n "$existing" ]] && break sleep 0.1 done elif [[ ${#headless_outputs[@]} -gt 1 ]]; then # Keep the first, log the rest. Removing outputs in sway during prestart can # cascade workspace re-assignment, so we err on the side of leaving them. log "Found ${#headless_outputs[@]} headless outputs; using $existing (extras left in place)" fi if [[ -z "$existing" ]]; then log "Failed to obtain a headless output; Sunshine will start without one." exit 0 fi log "Headless output present: $existing" # Sync sunshine.conf's output_name. Only touch the file if it's our managed # variant (has the management marker) AND the line has actually drifted. if [[ -f "$CONF" ]] && grep -qF '# managed-by: omarchy-moonlight' "$CONF"; then current="$(awk '/^output_name = / {print $3; exit}' "$CONF" 2>/dev/null || true)" if [[ "$current" != "$existing" ]]; then log "Updating sunshine.conf output_name: ${current:-(unset)} -> $existing" if grep -q '^output_name = ' "$CONF"; then sed -i "s|^output_name = .*|output_name = $existing|" "$CONF" else printf '\noutput_name = %s\n' "$existing" >> "$CONF" fi fi fi exit 0