#!/usr/bin/env bash

. lib.bash || exit

root=""
dbpath="$root/var/lib/pacman/local"

if (( $# )); then
	dirs=()
	for _pkg in "$@"; do
		dirs+=("$dbpath"/$_pkg-*/)
	done
else
	dirs=("$dbpath"/*/)
fi

for dir in "${dirs[@]}"; do
	pkg=${dir%/}
	pkg=${pkg##*/}

	if ! [[ -s "$dir/mtree" ]]; then
		warn "package '$pkg' is missing a mtree file"
		continue
	fi

	while read -r name rest; do
		if [[ $name == ./.@(BUILDINFO|CHANGELOG|INSTALL|PKGINFO) ]]; then
			continue
		fi
		name=/${name#./}
		if [[ $name == *\\* && $name != *\\@(12|012)* ]]; then
			# spaces and UTF-8 symbols are octal-encoded
			# (safeguard: do not decode if it contains a \n)
			name=$(unescape -a "$name")
		fi
		for arg in $rest; do
			k=${arg%%=*}
			v=${arg#*=}
			case $k in
			    sha256digest)
				printf '%s %s\n' "$v" "$name"
				;;
			esac
		done
	done < <(gzip -d < "$dir/mtree")
done
