#!/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 "pipewire-start first initcheck $INITCHECK"
if [[ "$INITCHECK" =~ "/lib/systemd/systemd" ]]; then
        INITSKIP="true"
fi

#second init check for system-shim configuration
#only if init skip is still false
if [ "$INITSKIP" = "false" ]; then
	INITCHECK=$(/usr/bin/ps -p 1 -o cmd -h)
	echo "pipewire-start second initcheck $INITCHECK"
	if [[ "$INITCHECK" =~ "/lib/systemd/systemd" ]]; then 
		INITSKIP="true"
	fi
fi

if [ "$INITSKIP" = "false" ]; then
	#start them up
	echo "not systemd, start pipewire"
	#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 &
else 
	echo "systemd detected, systemd will start pipewire"
fi

exit 0

