#!/bin/bash

ROOT=${ROOT:-/}

for contents in $(find ${ROOT}/var/db/pkg -name CONTENTS) ; do
	pkg_root=$(dirname ${contents})
	
	if [[ -f ${pkg_root}/soname.DEPEND || -f ${pkg_root}/soname.PROVIDE ]] ; then
		continue
	fi

	> ${pkg_root}/soname.DEPEND
	> ${pkg_root}/soname.PROVIDE

	for file in $(cat ${contents} | egrep ^obj | sed 's:obj \(.*\) [^ ]* [^ ]*:\1:') ; do
		f=$(file ${file})

		if [[ -z "${f/*SB executable*/}" || -z "${f/*SB shared object*/}" ]]; then
			soname=$(readelf -d ${file} | grep SONAME | sed 's/^.*\[\(.*\)\].*$/\1/')
			depend=$(readelf -d ${file} | grep NEEDED | sed 's/^.*\[\(.*\)\].*$/\1/')
					
			if [[ -n ${soname} ]] ; then
				echo "${soname} ${file}" >> ${pkg_root}/soname.PROVIDE
			fi

			for dep in ${depend} ; do
				echo "${dep} ${file}" >> ${pkg_root}/soname.DEPEND
			done
		fi
	done
done
