#!/bin/bash
# -*- mode: shell-script; indent-tabs-mode: t; sh-basic-offset: 8; sh-indentation: 8; tab-width: 8 -*-

PROG="$(basename ${0})"

tool_output_dir="${1}"
if [[ ! -d "${tool_output_dir}" ]]; then
	printf -- "%s: invalid tool output directory, '%s'\n" "${PROG}" "${tool_output_dir}" >&2
	exit 1
fi

pid_to_strace="${2}"
if [[ -z "${pid_to_strace}" ]]; then
	printf -- "%s: missing PID to strace\n" "${PROG}" >&2
	exit 1
fi

command -v strace > /dev/null
if [[ ${?} -ne 0 ]]; then
	printf -- "%s: missing 'strace' command\n" "${PROG}" >&2
	exit 1
fi

if [[ "${pid_to_strace}" == "0" ]]; then
	pids_to_strace=""
else
	pids_to_strace="${pid_to_strace}"
fi
pattern="${3}"
if [[ ! -z "${pattern}" ]]; then
	pids_to_strace="${pids_to_strace} $(pgrep "${pattern}")"
fi

for pid in ${pids_to_strace}; do
	strace_stdout_file=${tool_output_dir}/${PROG}-${pid}-stdout.txt
	strace_stderr_file=${tool_output_dir}/${PROG}-${pid}-stderr.txt

	strace_pid_file=${tool_output_dir}/${PROG}-${pid}.pid
	strace -p ${pid} -c -o "${strace_stdout_file}" 2> "${strace_stderr_file}" & echo ${!} > "${strace_pid_file}"
done

function _term {
	for strace_pid_file in ${tool_output_dir}/${PROG}-*.pid; do
		if [[ ! -f "${strace_pid_file}" ]]; then
			continue
		fi
		kill $(cat ${strace_pid_file}) && /bin/rm "${strace_pid_file}"
	done
}

trap _term SIGTERM

# Wait for all straces to complete
wait

for strace_pid_file in ${tool_output_dir}/${PROG}-*.pid; do
	/bin/rm -f "${strace_pid_file}"
done

exit 0
