#!/bin/sh
# mermaid-cli with the puppeteer config that passes --no-sandbox to headless
# Chromium. Ubuntu 24.04's AppArmor userns restriction kills Chromium's own
# sandbox, so without this nvim's mermaid rendering fails.
#
# It execs the real mmdc found later on PATH (the npm-global install), skipping
# itself. A bare `mmdc` reaches this wrapper only if ~/.local/bin comes before
# the npm-global bin on PATH, which is the order .zshrc sets.
set -eu

self=$(cd "$(dirname "$0")" && pwd -P)/$(basename "$0")
real=
IFS=:
for d in $PATH; do
	[ -n "$d" ] || continue
	c=$d/mmdc
	[ -f "$c" ] || continue
	[ -x "$c" ] || continue
	[ "$(cd "$d" && pwd -P)/mmdc" = "$self" ] && continue
	real=$c
	break
done
unset IFS

[ -n "$real" ] || { echo "mmdc: mermaid-cli is not installed (no other mmdc on PATH)" >&2; exit 127; }

cfg=${XDG_CONFIG_HOME:-$HOME/.config}/mermaid/puppeteer-config.json
if [ -r "$cfg" ]; then
	exec "$real" -p "$cfg" "$@"
fi
exec "$real" "$@"
