#!/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.

#######################################################################
# check icons in /usr/share/icons/hicolor/ and /usr/share/pixmaps.
# all icons must be world-readable, owned by root:root. the file type
# has to match the filename (e.g. a PNG file that's called "foo.gif"
# is a failure). for /usr/share/icons/hicolor/<size>, the image
# size has to match the directory name (e.g. 64x64).

nonimages=""

check_mime() {
	local file="$1"
	local havemime="$2"
	local wantmime="$3"

	#echo "check_mime $file $havemime $wantmime"

	if [ "$havemime" != "$wantmime" ]; then
		warn "bad filename extension: $file is $havemime, .$ext should be $wantmime"
	fi
}

check_image() {
	local f="$1"
	local size
	local bn="$( basename $f )"
	local ext="$( echo $bn | sed 's,.*\.\([^.]*\)$,\1,' )"
	[ "$ext" = "$f" ] && ext=""

	[ "$bn" = "theme" -o "$bn" = "icon-theme.cache" -o "$bn" = "index.theme" ] && return

	mime="$( file -L -z -b --mime-type "$f" )"
	case "$mime" in
		image/*) ;; # OK
		*) nonimages+="$f " ; return ;;
	esac

	# it's not real clear to me whether .bmp or .ico should be allowed
	# as icons. for now, just check the mime types.
	case "$ext" in
		""|".") badextensions+="$f " ;;
		PNG|png)           check_mime $f $mime image/png ;;
		GIF|gif)           check_mime $f $mime image/gif ;;
		JPG|jpg|JPEG|jpeg) check_mime $f $mime image/jpeg ;;
		XPM|xpm)           check_mime $f $mime image/x-xpmi ;;
		SVG|svg|SVGZ|svgz) check_mime $f $mime image/svg+xml ;;
		BMP|bmp)           check_mime $f $mime image/bmp ;;
		ICO|ico)           check_mime $f $mime image/vnd.microsoft.icon ;;
	esac

	# extract e.g. 64x64 or 128x128 from the path to the file.
	# this works for e.g. /usr/share/icons/hicolor/64x64/apps/blah.png,
	# but it's required to have / before and after the size, so an
	# icon named /usr/share/pixmaps/foo_32x32.png won't have its
	# size checked.
	size="$( echo $f | grep -o '/\([0-9][0-9]*\)x\1/' | cut -d/ -f2 )"

	if [ -n "$size" ]; then
		actualsize="$( identify "$f" | sed -n 's,.* \([0-9][0-9]*x[0-9][0-9]*\) .*,\1,p' )"
		if [ "$size" != "$actualsize" ]; then
			warn "incorrectly sized (or named) icon $f (should be $actualsize)"
		fi
	fi
}

for icondir in usr/share/pixmaps usr/share/icons/hicolor; do
	if [ -d "$icondir" ]; then
		files="$( find -L "$icondir" -type f )"
		for i in $files; do
			check_image $i
		done
	fi
done

[ "$nonimages" != "" ] && warn "non-image files in icon dirs:" && ls -ld $nonimages
