#!/bin/bash
# virgl_test_server wrapper for Zhaoxin cx4 iGPU hosts (selected automatically by
# smilebasic-launcher when the cx4 DRM driver is present).  Two transparent fixes:
#   1. this distro's virgl_test_server only accepts --socket-path=<p> (equals
#      form); smilebasic-daemon passes the space form, which the server misparses
#      as a trace-replay file and exits instantly.  Translate it.
#   2. preload virgl_cx4_glx_fix.so: virglrenderer reaches GLX through libepoxy,
#      whose resolved entrypoints misbehave on the cx4 vendor Mesa (BadMatch on
#      the per-context glXMakeContextCurrent).  The shim interposes the
#      epoxy_glX* dispatch pointers and forwards to real libGL, and forces a
#      pbuffer-capable fbconfig.  Result: hardware "ZX C-1190" contexts.
SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
# Prefer the virglrenderer 1.1.0 server shipped alongside this wrapper.  Distro
# builds vary far too much to rely on: Deepin 25's virgl-server is 0.8.2, whose
# vtest has neither --multi-clients nor --socket-path, so sb-daemon's invocation
# makes it print usage and exit -- no socket, silent software rendering.
if [ -n "${VIRGL_REAL_SERVER:-}" ]; then
  REAL="$VIRGL_REAL_SERVER"
elif [ -x "$SELF_DIR/virgl_test_server" ]; then
  REAL="$SELF_DIR/virgl_test_server"
else
  REAL=/usr/bin/virgl_test_server
fi
args=()
while [ $# -gt 0 ]; do
  case "$1" in
    --socket-path)   args+=("--socket-path=$2"); shift 2;;
    *)               args+=("$1"); shift;;
  esac
done
export LD_PRELOAD="${LD_PRELOAD:+$LD_PRELOAD:}$SELF_DIR/virgl_cx4_glx_fix.so"
exec "$REAL" "${args[@]}"
