#!/bin/sh

die() {
	if [ "$*" ]; then
		echo "$*" 1>&2
	fi
	exit 2
}

TARGET=$1
case "$TARGET" in
	-*|'') cat <<EOF
Usage: $0 <pkgname>

Checks the Slackware package database in /var/log/packages and returns
true (0) if <pkgname> is installed, false (1) otherwise.

If there's an error, the return status will be 2, which is still false,
but the caller can check for this by examining the \$? variable.

If standard output is a terminal, the full installed package
name (package-version-arch-build_tag) will be printed to stdout,
or "no package" if no such package is installed.

Like Slackware's installpkg, $0 respects the environment
variable ROOT, to operate on a mounted partition other than /.
EOF
	       ;;
esac

if [ "$2" != "" ]; then
	die "Usage: $0 <pkgname|--help>"
fi

cd $ROOT/var/log/packages || die "Are you sure this is Slackware?"
for i in ${TARGET}-*; do
	j=$(echo $i | rev | cut -d- -f4- | rev)
	if [ "$TARGET" = "$j" ]; then
		[ -t 1 ] && echo $i
		exit 0
	fi
done

[ -t 1 ] && echo "no package '$TARGET' installed"
exit 1