#!/bin/bash

# ------------------------------------------------------------------------
#                                                                        -
#  Created by Maxxim                                                     -
#  Date: 12/06/17                                                        -
#                                                                        -
# ------------------------------------------------------------------------


# --------------------------------
#  Functions                     -
# --------------------------------

# Print array [$1..$n: array elements]
function print_array() {
	local i
	local array=( "$@" )
	for ((i=0; i < ${#array[@]}; i++)); do
		echo "${array[i]}"
	done
}

# Check if array contains item [$1: item, $2..$n: array elements]
function in_array() {
	local i
	local item="$1"
	shift
	local array=( "$@" )
	for ((i=0; i < ${#array[@]}; i++)); do
		if [[ $item == "${array[i]}" ]]; then
			return 0
		fi
	done
	return 1
}


# --------------------------------
#  Main                          -
# --------------------------------

# Process command line
if (( $# < 1 )); then
	echo "Usage: $(basename "$0") <path-to-binary> <...>"
	exit 2
fi
binaries=( "$@" )

# Process binaries
libraries=()
re_ldd="^([^[:space:]]+) => ([^[:space:]]+) \((.*)\)"
for ((i=0; i < ${#binaries[@]}; i++)); do

	# Determine libraries used by binary
	binlibs=()
	while read -r line; do
		[[ $line =~ $re_ldd ]] && binlibs+=( ${BASH_REMATCH[2]} )
	done < <(ldd "${binaries[i]}")

	# Add libraries to global array
	libraries+=( "${binlibs[@]}" )

	# Print results for binary
	echo -e "\e[1mBinary '${binaries[i]}':\e[0m"
	print_array "${binlibs[@]}"
	echo -e "\e[1m-> ${#binlibs[@]} libraries\e[0m"
	echo

done

# Sort, unique and print required libraries
libraries=( $(print_array "${libraries[@]}" | sort | uniq) )
echo -e "\e[1mRequired libraries:\e[0m"
print_array "${libraries[@]}"
echo -e "\e[1m-> ${#libraries[@]} libraries\e[0m"
echo

# For each library, find the package providing it
packages=()
echo -en "\e[1mMatching libraries to packages...\e[0m "
for ((i=0; i < ${#libraries[@]}; i++)); do
	packages+=( $(qfile --quiet --nocolor "${libraries[i]}") )
done
echo -e "\e[1;32mok\e[0m"
echo

# Sort, unique and print required packages
packages=( $(print_array "${packages[@]}" | sort | uniq) )
echo -e "\e[1mRequired packages:\e[0m"
print_array "${packages[@]}"
echo -e "\e[1m-> ${#packages[@]} packages\e[0m"
echo
