#!/bin/sh
# DPHMS payload v29: audio inside the container.
# v28 and earlier pointed every app at PULSE_SERVER=127.0.0.1:4713, a host-side PulseAudio that was never
# shipped, so apps and the panel volume plugin got "connection refused" and retried forever (the
# 'Disconnected from the PulseAudio server. Attempting to reconnect' warnings).
# Order: (1) something already serving 4713 on the phone (a PulseAudio app, e.g. Termux's) = REAL sound,
#        (2) otherwise run PulseAudio INSIDE the container with a null sink = no errors, volume works, silent.
PORT=4713
up() { python3 - "$PORT" <<'PY' 2>/dev/null
import socket,sys
s=socket.socket(); s.settimeout(1.5)
try: s.connect(("127.0.0.1",int(sys.argv[1]))); sys.exit(0)
except Exception: sys.exit(1)
PY
}
export XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR:-/tmp/xdg-runtime}
mkdir -p "$XDG_RUNTIME_DIR" /root/.config/pulse
MODE=none
if up; then
  MODE="phone (host PulseAudio on 127.0.0.1:$PORT, real sound)"
elif command -v pulseaudio >/dev/null 2>&1; then
  # no filesystem unix sockets under proot: TCP only, loopback only
  cat > /root/.config/pulse/default.pa <<'PA'
.fail
load-module module-null-sink sink_name=dphms sink_properties=device.description=DPHMS-Audio
load-module module-native-protocol-tcp listen=127.0.0.1 port=4713 auth-anonymous=1
set-default-sink dphms
PA
  printf 'autospawn = no\ndaemon-binary = /usr/bin/pulseaudio\n' > /root/.config/pulse/client.conf
  pkill -x pulseaudio 2>/dev/null; sleep 1
  pulseaudio --daemonize=yes --exit-idle-time=-1 --disallow-exit --use-pid-file=no \
    --disable-shm=yes --log-target=file:/root/.vnc/pulse.log -n -F /root/.config/pulse/default.pa 2>/dev/null
  i=0; while [ $i -lt 8 ]; do up && break; sleep 1; i=$((i+1)); done
  if up; then MODE="inside DPHMS OS (virtual speaker, silent; no errors)"; else MODE="FAILED to start (see /root/.vnc/pulse.log)"; fi
fi
# every app in the desktop talks to loopback TCP
printf 'default-server = 127.0.0.1:%s\nautospawn = no\n' "$PORT" > /root/.config/pulse/client.conf
echo "── DPHMS audio ──"
echo "  server : $MODE"
command -v pactl >/dev/null 2>&1 && echo "  sinks  : $(PULSE_SERVER=127.0.0.1:$PORT timeout 4 pactl list short sinks 2>/dev/null | awk '{print $2}' | tr '\n' ' ')"
