#!/bin/sh
#find-debuginfo.sh - automagically generate debug info and file list
#for inclusion in an rpm spec file.

if [ -z "$1" ] ; then BUILDDIR="."
else BUILDDIR=$1
fi

LISTFILE=$BUILDDIR/debugfiles.list
SOURCEFILE=$BUILDDIR/debugsources.list

debugdir="${RPM_BUILD_ROOT}/usr/lib/debug"

echo -n > $SOURCEFILE

# Strip ELF binaries
for f in `find $RPM_BUILD_ROOT ! -path "${debugdir}/*.debug" -type f \( -perm +111 -or -name "*.so*" -or -name "*.ko" \) `
do
	case $(objdump -h $f 2>/dev/null | egrep -o '(debug[\.a-z_]*|gnu.version)') in
	    *debuglink*) continue ;;
	    *debug*) ;;
	    *gnu.version*)
		echo "WARNING: "`echo $f | sed -e "s,^$RPM_BUILD_ROOT/*,/,"`" is already stripped!"
		continue
		;;
	    *) continue ;;
	esac

	dn=$(dirname $f | sed -n -e "s#^$RPM_BUILD_ROOT##p")
	bn=$(basename $f .debug).debug

	debugdn="${debugdir}${dn}"
	debugfn="${debugdn}/${bn}"
	[ -f "${debugfn}" ] && continue

	echo extracting debug info from $f
	mode=$(stat -c %a $f)
	chmod +w $f
	/usr/lib/rpm/debugedit -b "$RPM_BUILD_DIR" -d /usr/src/debug -l "$SOURCEFILE" "$f"

	# A binary already copied into /usr/lib/debug doesn't get stripped,
	# just has its file names collected and adjusted.
	case "$dn" in
	/usr/lib/debug/*) continue ;;
	esac

	mkdir -p "${debugdn}"
	objcopy --only-keep-debug $f $debugfn || :
	strip_option="--strip-all"
	case "$f" in
	    *.ko|*.a) strip_option="--strip-debug" ;;
	esac
	if test -n "$STRIP_KEEP_SYMTAB" ; then
	    strip_option="--strip-debug"
	fi
	if test "$NO_DEBUGINFO_STRIP_DEBUG" = true ; then
	    strip_option=
	fi
	objcopy --add-gnu-debuglink=$debugfn $strip_option $f || :
	chmod $mode $f
done

for f in `find $RPM_BUILD_ROOT ! -path "${debugdir}/*.debug" -type f \( -name "*.exe.mdb" -or -name "*.dll.mdb" \) `
do
	dn=$(dirname $f | sed -n -e "s#^$RPM_BUILD_ROOT##p")
	case "$dn" in
	/usr/lib/debug/*) continue ;;
	esac
	debugdn="${debugdir}${dn}"
	mkdir -p "${debugdn}"
	mv "$f" "${debugdn}"
done


mkdir -p ${RPM_BUILD_ROOT}/usr/src/debug
(cd $RPM_BUILD_DIR; LANG=C sort -z -u | cpio -pd0m ${RPM_BUILD_ROOT}/usr/src/debug) < $SOURCEFILE

# trying to replace dangling and/or absolute symlink
DBASE=${RPM_BUILD_ROOT}/usr/src/debug
for link in `find $DBASE -type l -printf "%P\n"` ; do
	link_file=`readlink $RPM_BUILD_DIR/$link`
	case $link_file in
	    /*) is_abs=true ;;
	    *)  is_abs= ;;
	esac
	if test ! -e "$DBASE/$link" -o -n "$is_abs" ; then # dangling
		rm -f "$DBASE/$link"
		cp "`readlink -f $RPM_BUILD_DIR/$link`" "$DBASE/$link"
	fi
done

{
	test -d ${RPM_BUILD_ROOT}/usr/lib/debug && echo /usr/lib/debug
	echo /usr/src/debug
} > $LISTFILE

for p in $(<$LISTFILE); do
  find $RPM_BUILD_ROOT/$p -type f -print0 | xargs -0 -r chmod 0644
  find $RPM_BUILD_ROOT/$p -type d -print0 | xargs -0 -r chmod 0755
done
