#!/bin/sh -

# whichpkg - attempt to output the given files installation packages
# Steve Kinzler, steve@kinzler.com, Dec 09/Oct 15/Nov 23
# https://kinzler.com/me/home.html#unixuni

case "$1" in
-h)	(echo "usage: $0 [ file ... ]"
	 echo 'With no arguments, list all installed packages.') 1>&2; exit 1;;
esac

if   (dpkg     --version) > /dev/null 2>&1 &&
     (rpm      --version) > /dev/null 2>&1; then
	if grep -s fedora /etc/os-release > /dev/null; then tool=rpm
	else						    tool=dpkg
	fi
elif (dpkg     --version) > /dev/null 2>&1; then tool=dpkg
elif (rpm      --version) > /dev/null 2>&1; then tool=rpm
elif (apt-file --version) > /dev/null 2>&1; then tool=apt	# slow
else echo "$0: cannot find a packaging program" 1>&2; exit 2
fi
# AIX has `lslpp -w` in case we ever want to support that

case "$#" in
0)	case "$tool" in
	rpm)	rpm -qa;;
	*)	dpkg -l | sed -n 's/^ii  *\([^ ]*\)  *\([^ ]*\).*$/\1 \2/p';;
	esac | sort
	exit;;
esac

nopkg='not owned by any package'
nopath='no path found matching pattern'
pwd="`pwd`"
case "`pwd`" in
/)	pwd=;;
esac

for file
do
	case "$tool" in
	rpm)	echo "$file:	"`rpm -qf -- "$file" |
				  sed "s/.*\($nopkg\).*/\1/; \\$q; s/$/,/"`;;

	dpkg)	case "$file" in
		/*)	arg="$file";;
		*)	arg="$pwd/$file";;
		esac
		echo "$file:	"`dpkg -S -- "$arg" 2>&1 |
			sed 's/^dpkg: .* \(not found\)\.*$/\1/
			     s/^dpkg-query: \('"$nopath"'\).*$/\1/
			     /^diversion by /d; s/: .*//; 1q'`;;

	apt)	case "$file" in
		/)	echo "$file:	not found"; continue;;
		/*)	arg="$file";;
		*)	arg="$pwd/$file"
		esac
		echo "$file:	"`apt-file -lF find "$arg" |
				  sed '$q; s/$/,/'` |
		sed 's/\(:	\)$/\1not found/';;
	esac
done
