#!/bin/sh -efu
#
# Copyright (C) 2000-2005  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2007       Alexey Tourbin <at@altlinux.org>
#
# Top-level strace(1) wrapper, prints system calls and filenames.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

PROG=strace_files

argv=`getopt -n "$PROG" -o +o: -l output:,trace:,help -- "$@"` || exit 1
eval set -- "$argv"

target=/dev/stdout
trace=

while :; do
	case "$1" in
		--help)
			echo "Usage: $PROG [-o|--output=FILE] [--trace=syscall1,...] COMMAND..."
			exit ;;
		-o|--output)
			shift
			target="$1"
			shift ;;
		--trace)
			shift
			[ -z "$trace" ] && trace="$1" || trace="$trace,$1"
			shift ;;
		--)
			shift
			break ;;
		*)
			echo "$PROG: unrecognized option: $1" >&2
			exit 1
	esac
done

if [ $# = 0 ]; then
	echo "$PROG: not enough arguments" >&2
	exit 1
fi

: >"$target"

exit_handler()
{
	local rc=$1
	rm -rf -- "$workdir"
	exit $rc
}

trap 'exit 143' HUP INT QUIT PIPE TERM
workdir="$(mktemp -dt "$PROG.XXXXXXXXXX")"
trap 'exit_handler $?' EXIT

unset TRACE_FILELIST ||:
TRACE_FILELIST="$workdir"/trace_filelist

if [ -n "${TRACE_FILES-}" ]; then
	echo "$TRACE_FILES" |
	while IFS= read -r f; do
		[ -z "$f" ] && continue
		echo "$f"
	done >>"$TRACE_FILELIST"
	export TRACE_FILELIST
fi

if [ -n "${TRACE_PACKAGES-}" ]; then
	rpmquery -l -- $TRACE_PACKAGES |
	while IFS= read -r f; do
		[ -d "$f" ] && continue
		echo "$f"
	done >>"$TRACE_FILELIST"
	export TRACE_FILELIST
fi

spp_output="$workdir"/spp_output

rc=0
strace -qq -f -z --seccomp-bpf -e signal=none -e trace="${trace:-file}" \
	-o "|/usr/share/buildreqs/spp >$spp_output" -- "$@" ||
	rc=$?

[ -s "$spp_output" ] || exit $rc
LC_COLLATE=C sort -u -k2 -k1 -o "$target" "$spp_output"
exit $rc
