#!/bin/sh

#usage:  file/to/check [/path/tp/dpkg-query [mode]]
# see if $1 was installed by dpkg
dpkg_query="${2-/usr/bin/dpkg-query}"
mode="${3-rt}"
if [ ! -x "${dpkg_query}" ] || [ "${mode}" = "pm" ]; then
	# not Debian or using -r
	echo "$1"
	exit 0
fi
file_to_report="/${1#/}" # ensure 1 leading '/'

package=$("${dpkg_query}" --search -- "$file_to_report" 2>/dev/null)
if [ -z "$package" ]; then
	# dpkg-query does not understand usrmerge
	case "$file_to_report" in
		# dirs which become symlinks (see /usr/lib/usrmerge/convert-usrmerge)
		/bin/*|/sbin/*|/lib/*|/lib64/*|/lib32/*|/libo32/*|/libx32/*)
			# /bin/apt not found because /usr/bin/apt shipped
			package=$("${dpkg_query}" --search -- "/usr$file_to_report" 2>/dev/null)
			;;
		/usr/bin/*|/usr/sbin/*|/usr/lib/*|/usr/lib64/*|/usr/lib32/*|/usr/libo32/*|/usr/libx32/*)
			# /usr/bin/bash not found because /bin/bash shipped
			package=$("${dpkg_query}" --search -- "${file_to_report#/usr}" 2>/dev/null)
			;;
	esac
fi
if [ -n "$package" ]; then
	# package is <package>: /path/to/file
	package="From Debian package: ${package%:*}"
else
	package="Not from a Debian package"
fi
# nb: $1 may be intentionally missing a /
echo "$1 [$package]"
exit 0
