set -e
read filename

ICON_MAXSIZE=512

if [ "${filename%%:*}" = xdgicon ]; then
    filename="$(/usr/lib/qubes/xdg-icon "${filename#*:}" "$ICON_MAXSIZE")"
    forcesize="$ICON_MAXSIZE"

    [ -n "${filename}" ]
elif [ "${filename}" = "-" ] || [ "${filename##*:}" = "-" ]; then
    tmpfile="$(mktemp /tmp/qimg-XXXXXXXX)"
    cat > "${tmpfile}"
    if [ "${filename##*:}" = "-" ]; then
        filename="${filename%:*}:${tmpfile}"
    else
        filename="${tmpfile}"
    fi
elif ! [ -r "${filename}" ]; then
    exit 1
fi

s="$(identify -format '%w %h %m' "$filename")"
w="$(echo "$s"|cut -d " " -f 1)"
h="$(echo "$s"|cut -d " " -f 2)"
m="$(echo "$s"|cut -d " " -f 3)"
if [ "$m" = SVG ]; then
    if [ -n "$forcesize" ]; then
        w="$forcesize"
        h="$forcesize"
    fi
    tmpfile2="$(mktemp /tmp/qimg-XXXXXXXX.png)"
    rsvg-convert -w "$w" -h "$h" -o "$tmpfile2" "$filename"
    filename="$tmpfile2"
fi
echo "$w $h"
convert -depth 8 -size "${w}x${h}" "$filename" rgba:-

[ -n "${tmpfile}" ] && rm -f "${tmpfile}" || true
[ -n "${tmpfile2}" ] && rm -f "${tmpfile2}" || true

# vim: ft=sh ts=4 sw=4 et