#! /bin/bash

# Create symlinks for libraries in TARGET_DIR for which there is
# no *.so link for the linker.  Make links to the shortest name - they
# are less likely to change on update.  Preserve local libraries.

: ${TARGET_DIR=/usr/local/lib}

# Clean up old links
for lib in $TARGET_DIR/lib*.so; do
	test -L $lib || continue
	link=$(readlink $lib)
	case $link in
		/lib/*.so.*) rm -f $lib ;;
		/usr/lib/*.so.*) rm -f $lib ;;
		/usr/X11R6/lib/*.so.*) rm -f $lib ;;
	esac
done

# Make new links
for lib in /usr/lib/lib*.so.* /lib/lib*.so.* /usr/X11R6/lib/lib*.so.*; do
	solib=${lib%.so*}.so

	# Linker already looks in /usr/lib
	test -e /usr/lib/${solib##*/} && continue

	solibmin=$(ls ${solib}.* | sort | head -1)
	test $lib != $solibmin && continue
	target=$TARGET_DIR/${solib##*/}

	# Never overwrite non-symlinks
	if test -e $target -a ! -L $target; then
		echo "Preserving $target - not a symlink"
		continue
	fi
	echo "Linking $solibmin"
	ln -nsf $solibmin $target
done
