#!	/bin/sh

set -e
# set -v
# set -x

ldd_succeeds () {
	for i in $*; do {
		ldd $i 2>/dev/null >/dev/null
		if [ $? -eq 0 ]; then
			echo $i
		fi
	}; done
}

if [ $# -lt 4 ]; then
	echo "Usage: $0 soname /usr/lib/library_pic.a output.so.x file [file ...]" 1>&2
	echo
	echo "	Generate a subset shared library to resolve symbols in the"
	echo "	executable programs given on the command line."
	exit -1
fi

# Kludge because __llseek, etc. is loaded only if needed.
# Are these all still necessary?
required_symbols="-u __llseek -u llseek -u __srandom -u sigaddset"
 

arch=`dpkg --print-architecture`

emulation=""
case $arch in
i386)
	emulation="-m elf_i386"
	ldso=ld-linux.so.2
;;
m68k)
	emulation="-m m68kelf"
	ldso=ld.so.1
;;
powerpc)
	emulation="-m elf32ppc"
	ldso=ld.so.1
;;
sparc)
	emulation="-m elf32_sparc"
	ldso=ld-linux.so.2
;;
esac

t=/var/tmp
soname=$1
shift
input_library=$1
shift
output=$1
shift

EXECUTABLES="`ldd_succeeds $*`"

command="cc -nostdlib -nostartfiles -o /var/tmp/lib.$$ $emulation -shared -Wl,-dynamic-linker=/lib/$ldso -Wl,-soname -Wl,$soname -s $required_symbols"

# Uncomment the following line to make ld dump a full load of info about 
# symbols, global common storage allocation and cross references.
#command="$command -Wl,-M -Wl,--cref"

command="$command `nm --dynamic --no-sort $EXECUTABLES | sed \
-e '/:$/d' \
-e '/^$/d' \
-e '/^.* $/d' \
-e 's/^.* //' \
-e '/^_DYNAMIC$/d' \
-e '/^_GLOBAL_OFFSET_TABLE_$/d' \
-e '/^__CTOR_LIST__$/d' \
-e '/^__DTOR_LIST__$/d' \
-e '/^__bss_start$/d' \
-e '/^_edata$/d' \
-e '/^_end$/d' \
-e '/^_etext$/d' \
-e '/^_fini$/d' \
-e '/^_init$/d' \
-e 's/@.*//' \
-e 's/^/-u /' \
| sort -u`"

command="$command $input_library -lgcc"
$command
strip --remove-section=.note --remove-section=.comment --remove-section=.debug \
 /var/tmp/lib.$$
mv /var/tmp/lib.$$ $output
