#!/usr/bin/env bash
#
# lddd - find broken library links on your machine
#
# License: Unspecified

. "$(librelib messages)"

usage() {
	print "Usage: %s [OPTIONS]" "${0##*/}"
	print "Find broken library links on your machine."
	echo
	prose "Scans \$PATH and library directories for ELF files with
	       references to missing shared libraries."
	echo
	print "Options:"
	flag \
		"-h, --help" "Show this message"
}

mode=run
if ! args="$(getopt -n "${0##*/}" -o 'h' -l 'help' -- "$@")"; then
	mode=errusage
else
	eval "set -- $args"
	while true; do
		flag=$1
		shift
		case "$flag" in
			-h | --help) mode=usage ;;
			--) break ;;
			*) panic 'unhandled flag: %q' "$flag" ;;
		esac
	done
	if [[ $mode == run && $# -gt 0 ]]; then
		gnuerror 'Extra arguments: %s' "$*"
		mode=errusage
	fi
fi
case "$mode" in
	errusage)
		print "Try '%s --help' for more information." "${0##*/}" >&2
		exit $EXIT_INVALIDARGUMENT
		;;
	usage)
		usage
		exit $EXIT_SUCCESS
		;;
	run) : ;;
	*) panic 'invalid mode: %q' "$mode" ;;
esac

ifs=$IFS
IFS="${IFS}:"

libdirs="/lib /usr/lib /usr/local/lib $(cat /etc/ld.so.conf.d/*)"
extras=

TEMPDIR=$(mktemp -d --tmpdir lddd-script.XXXX)

msg 'Go out and drink some tea, this will take a while :) ...'
#  Check ELF binaries in the PATH and specified dir trees.
for tree in $PATH $libdirs $extras; do
	msg2 "DIR %s" "$tree"

	#  Get list of files in tree.
	files=$(find "$tree" -type f ! -name '*.a' ! -name '*.la' ! -name '*.py*' ! -name '*.txt' ! -name '*.h' ! -name '*.ttf' ! \
	-name '*.rb' ! -name '*.ko' ! -name '*.pc' ! -name '*.enc' ! -name '*.cf' ! -name '*.def' ! -name '*.rules' ! -name \
	'*.cmi' ! -name  '*.mli' ! -name '*.ml' ! -name '*.cma' ! -name '*.cmx' ! -name '*.cmxa' ! -name '*.pod' ! -name '*.pm' \
	! -name '*.pl' ! -name '*.al' ! -name '*.tcl' ! -name '*.bs' ! -name '*.o' ! -name '*.png' ! -name '*.gif' ! -name '*.cmo' \
	! -name '*.cgi' ! -name '*.defs' ! -name '*.conf' ! -name '*_LOCALE' ! -name 'Compose' ! -name '*_OBJS' ! -name '*.msg' ! \
	-name '*.mcopclass' ! -name '*.mcoptype')
	IFS=$ifs
	for i in $files; do
		if (( $(file "$i" | grep -c 'ELF') != 0 )); then
			#  Is an ELF binary.
			if (( $(ldd "$i" 2>/dev/null | grep -c 'not found') != 0 )); then
				#  Missing lib.
				echo "$i:" >> "$TEMPDIR/raw.txt"
				ldd "$i" 2>/dev/null | grep 'not found' >> "$TEMPDIR/raw.txt"
			fi
		fi
	done
done
grep '^/' "$TEMPDIR/raw.txt" | sed -e 's/://g' >> "$TEMPDIR/affected-files.txt"
# invoke pacman
while read -r i; do
	pacman -Qo "$i" | awk '{print $4,$5}' >> "$TEMPDIR/pacman.txt"
done < "$TEMPDIR/affected-files.txt"
# clean list
sort -u "$TEMPDIR/pacman.txt" >> "$TEMPDIR/possible-rebuilds.txt"

msg "Files saved to %s" "$TEMPDIR"
