#!/bin/bash

log=${1}

usage() {
	echo "${0##*/} compilation_log"
	echo "  Returns a list of -llibrary gcc link commands."
	exit 1
}

if [[ $# -ne 1 ]]; then
	usage
fi

get_libnames() {
	for linkline in $(grep '\b-l[[:alnum:]].*\b' ${1}); do
		if [[ "${linkline}" = -l[a-zA-Z]* ]]; then
			echo ${linkline}
		fi
	done \
		| sort | sed -e "s:\.*$::g" -e "s:|::g" -e "s:\"::g" \
		| uniq | sed -e "s:^-l::g"
}

get_libdirs() {
	cat /etc/ld.so.conf | sed -e "/^#/d"
}

libdirs="/lib /usr/lib $(get_libdirs)"

echo "Analyzing log ..."
libnames="$(get_libnames ${1})"

echo "Looking for libraries ..."
for libname in ${libnames}; do
	static=0
	shared=0
	if grep '\b-l[[:alnum:]].*\b' ${1} | grep "\b-l${libname}\b" | grep -q '\b-static\b'; then
		static=1
	fi
	if ! grep '\b-l[[:alnum:]].*\b' ${1} | grep "\b-l${libname}\b" | grep -q '\b-static\b'; then
		shared=1
	fi
	staticlibname="lib${libname}.a"
	sharedlibname="lib${libname}.so"
	if [[ ${static} -eq 1 ]]; then
		echo -n "  Looking for ${staticlibname} ... "
		for libdir in ${libdirs}; do
			found=0
			if [[ -e ${libdir}/${staticlibname} ]]; then
				libpaths="${libpaths} ${libdir}/${staticlibname}"
				found=1
				echo "OK"
				break
			fi
		done
		if [[ ${found} -ne 1 ]]; then
			echo "Not found!"
		fi
	fi
	if [[ ${shared} -eq 1 ]]; then
		echo -n "  Looking for ${sharedlibname} ... "
		for libdir in ${libdirs}; do
			found=0
			if [[ -e ${libdir}/${sharedlibname} ]]; then
				libpaths="${libpaths} ${libdir}/${sharedlibname}"
				found=1
				echo "OK"
				break
			fi
		done
		if [[ ${found} -ne 1 ]]; then
			echo "Not found!"
		fi
	fi
done

echo "Tracing libraries back to packages ..."
echo
if [[ -x $(which equery 2> /dev/null) ]]; then
	equery -q belongs ${libpaths} | cut -d'(' -f1
elif [[ -x $(which rpm 2> /dev/null) ]]; then
	rpm -qf ${libpaths}
else
	echo "Couldn't find package query tool! Printing libpaths instead."
	echo
	for libpath in ${libpaths}; do
		echo ${libpath}
	done
fi
