#!/bin/sh
# Run the local OCI image against the current user's Wayland/PipeWire session.
set -eu

fail() { printf 'moonmix-container: %s\n' "$*" >&2; exit 1; }
command -v podman >/dev/null 2>&1 || fail "install rootless Podman first"
[ "$#" -eq 0 ] || fail "this launcher does not take arguments"
[ -n "${XDG_RUNTIME_DIR:-}" ] || fail "XDG_RUNTIME_DIR is not set"
[ -n "${WAYLAND_DISPLAY:-}" ] || fail "a Wayland session is required"

uid=$(id -u)
gid=$(id -g)
[ "$uid" -ne 0 ] || fail "run this as your desktop user, not root"
case "$WAYLAND_DISPLAY" in
  /*) wayland_socket=$WAYLAND_DISPLAY ;;
  *) wayland_socket=$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY ;;
esac
case "${PIPEWIRE_REMOTE:-pipewire-0}" in
  /*) pipewire_socket=$PIPEWIRE_REMOTE ;;
  *) pipewire_socket=${PIPEWIRE_RUNTIME_DIR:-$XDG_RUNTIME_DIR}/${PIPEWIRE_REMOTE:-pipewire-0} ;;
esac
[ -S "$wayland_socket" ] || fail "Wayland socket not found: $wayland_socket"
[ -S "$pipewire_socket" ] || fail "PipeWire socket not found: $pipewire_socket"

set -- podman run --rm --pull=never \
  --userns=keep-id --user "$uid:$gid" \
  --network=none --cap-drop=all --security-opt=no-new-privileges \
  --read-only \
  --tmpfs /tmp:rw,nosuid,nodev \
  --env XDG_ACTIVATION_TOKEN --env DESKTOP_STARTUP_ID \
  --env XDG_RUNTIME_DIR=/tmp/moonmix-runtime \
  --env PIPEWIRE_RUNTIME_DIR=/run/moonmix \
  --env PIPEWIRE_REMOTE=pipewire-0 \
  --env WAYLAND_DISPLAY=/run/moonmix/wayland-0 \
  --mount "type=bind,src=$wayland_socket,dst=/run/moonmix/wayland-0,ro" \
  --mount "type=bind,src=$pipewire_socket,dst=/run/moonmix/pipewire-0,ro"

# The portal supplies desktop appearance settings. Do not expose the rest of
# XDG_RUNTIME_DIR (which can contain credentials and unrelated service sockets).
if [ -S "$XDG_RUNTIME_DIR/bus" ]; then
  set -- "$@" \
    --mount "type=bind,src=$XDG_RUNTIME_DIR/bus,dst=/run/moonmix/bus,ro" \
    --env DBUS_SESSION_BUS_ADDRESS=unix:path=/run/moonmix/bus
else
  set -- "$@" --env DBUS_SESSION_BUS_ADDRESS=unix:path=/run/moonmix/no-bus
fi

exec "$@" "${MOONMIX_IMAGE:-localhost/moonmix:latest}"
