#!/bin/sh

# sbopkglint test, must be sourced by sbopkglint (not run standalone).

# PKG, PRGNAM, VERSION, ARCH are set by sbopkglint. also the current
# directory is the root of the installed package tree.

#######################################################################
# if the package contains any files in /usr/share/applications/, they
# must be named *.desktop, must pass desktop-file-validate, and must
# be mode 644, owner root:root.
#
# the one exception: files named *-mimeapps.list are allowed (though they
# are not checked for content). see:
# https://specifications.freedesktop.org/mime-apps-spec/mime-apps-spec-latest.html

check_desktop_dir() {
	local dir="$1"

	if [ -f "$dir" ]; then
		warn "$dir exists, but is a file, not a directory!"
		return
	fi

	[ -d "$dir" ] || return

	for f in $dir/*; do
		[ -e "$f" ] || continue

		[ "$f" = "usr/share/applications/mimeinfo.cache" ] && continue
		[ "$f" = "usr/share/applications/screensavers" ] && continue

		[ "$( stat -Lc '%a %U %G' "$f" )" = "644 root root" ] || \
			ls -bld "$f" >> .badperms.$$

		case "$f" in
			*.desktop) desktop-file-validate "$f" || ls -bld "$f" >> .baddtop.$$ ;;
			*-mimeapps.list) ;; # OK, ignore
			*) ls -bld "$f" >> .nondtop.$$ ;;
		esac
	done
}

for dir in usr/share/applications usr/share/applications/screensavers; do
	check_desktop_dir "$dir"
done

if [ -s .badperms.$$ ]; then
	warn "bad permissions/owner on .desktop files (should be 0644 root:root):"
	cat .badperms.$$
fi

if [ -s .baddtop.$$ ]; then
	warn ".desktop files fail to validate:"
	cat .baddtop.$$
fi

if [ -s .nondtop.$$ ]; then
	warn "unknown file (not .desktop) in desktop dir:"
	cat .nondtop.$$
fi

rm -f .badperms.$$ .baddtop.$$ .nondtop.$$
