#!/bin/bash

INITSKIP="false"
configfile="$HOME/.config/MX-Linux/pipewire-start.conf"
if [ ! -e "$configfile" ]; then
	echo "#delay wireplumber session manager to give pipewire time to settle before launch" > "$configfile"
	echo "wireplumber_delay=2" >> "$configfile"
fi

source "$configfile"

#first init check for pure systemd, no shim
INITCHECK=$(readlink /usr/sbin/init)
echo $INITCHECK
if [ "$INITCHECK" = "/lib/systemd/systemd" ]; then
        INITSKIP="true"
fi

#second init check for system-shim configuration
INITCHECK=$(/usr/bin/ps -p 1 -o cmd -h)
echo $INITCHECK
if [ "$INITCHECK" = "/lib/systemd/systemd" ]; then 
	  INITSKIP="true"
fi

#else start them up
echo "start pipewire"

if [ "$INITSKIP" = "false" ]; then
	#kill existing servers per user
	if [ -n "$(pgrep -x -u $USER pipewire)" ]; then
		pkill -x -u $USER pipewire
	fi
	if [ -n "$(pgrep -x -u $USER pipewire-pulse)" ]; then
		pkill -x -u $USER pipewire-pulse
	fi
	if [ -n "$(pgrep -x -u $USER wireplumber)" ]; then
    	pkill -u $USER wireplumber
	fi
	#start up new servers
	/usr/bin/pipewire 2>/dev/null &
 	/usr/bin/pipewire-pulse &
 	#ignore config file value if not a postive non-zero number
 	check=$(echo "$wireplumber_delay>0" | bc -l)
 	if [ $check == 1 ]; then
		echo "delay wireplumber server start $wireplumber_delay seconds"
		echo "configurable in $configfile"
		sleep $wireplumber_delay
	fi
	/usr/bin/wireplumber 2>/dev/null &
fi

exit 0

