#!/bin/sh -e
#
# Copyright (C) 2000-2005  Dmitry V. Levin <ldv@altlinux.org>
#
# Generates list of file requires for given command.
#
# 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="${0##*/}"

if [ $# -le 1 ]; then
	echo "Usage: $PROG <file-where-to-store-requires> <program> [program-args]" >&2
	exit 1
fi

TARGET="$1"
shift
: >"$TARGET"

unsorted="$(mktemp -t "$PROG.XXXXXXXXXX")"
export LOCKFILE="$(mktemp -t "$PROG.XXXXXXXXXX")"

RETVAL=

real_exit()
{
	rm -f -- "$unsorted" "$LOCKFILE"
	exit $RETVAL
}

plain_exit()
{
	RETVAL=$?
	trap - EXIT
	real_exit
}

sort_exit()
{
	RETVAL=$?
	trap - EXIT
	if [ "$RETVAL" = 0 ]; then
		LC_COLLATE=C sort -u -- "$unsorted" > "$TARGET" ||:
	fi
	real_exit
}

trap plain_exit HUP PIPE INT TERM
trap sort_exit QUIT EXIT

strace -kqfF -e trace=file -o "|/usr/share/buildreqs/filter_strace >$unsorted" -- "$@"

# Wait for filter_strace.
while [ -f "$LOCKFILE" ]; do
	usleep 100000
done
