#!/bin/bash
# Copyright 2020 - 2025, project-repo and the cagebreak contributors
# SPDX-License-Identifier: MIT
#
# This script displays the process names of the views on the current workspace.

named_pipe_send="$(mktemp -u)"
named_pipe_recv="$(mktemp -u)"
mkfifo "${named_pipe_send}"
mkfifo "${named_pipe_recv}"
nc -U "${CAGEBREAK_SOCKET}" < "${named_pipe_send}" > "${named_pipe_recv}"&
# The file descriptor 3 is set up to send commands to cagebreak and file
# descriptor 4 can be used to read events. Notice that events will pile up in
# file descriptor 4, so it is a good idea to continuously read from it or to
# clear it before starting a new transaction.
exec 3>"${named_pipe_send}"
exec 4<"${named_pipe_recv}"
# When the script exits, the os will clean up the pipe
rm "${named_pipe_recv}"
rm "${named_pipe_send}"

echo "dump" >&3

while IFS= read -r -d $'\0' event
do
	# Remove the cg-ipc header
	event="${event:6}"
	if [[ "$(echo "${event}" | jq ".event_name")" = "\"dump\"" ]]
	then
		curr_output="$(echo "${event}"|jq ".curr_output")"
		curr_workspace="$(echo "${event}"|jq -r ".outputs.${curr_output}.curr_workspace")"
		# Print the process names of the view on the current workspace. jq retrieves
		# their PID and ps is then used to retrieve the process names.
		# shellcheck disable=2046
		(echo -n "message ";ps -o comm=Command -p $(echo "${event}"|jq -r ".outputs.${curr_output}.workspaces[$((curr_workspace-1))].views[].pid")|tail +2|sed ':a; N; $!ba; s/\n/||/g') >&3
		break
	fi
done <&4
