#!/bin/sh
#
# Updates the appstream AppData cache during installation of packages and
# deletes it when AppStream is removed
#
# Arguments:	$ACTION = [run/targets]
#		$TARGET = [post-install/post-remove]
#		$PKGNAME
#		$VERSION
#		$UPDATE = [yes/no]
#
ACTION="$1"
TARGET="$2"
PKGNAME="$3"
VERSION="$4"
UPDATE="$5"

# The appstreamcli binary program.
APPSTREAMCLI="usr/bin/appstreamcli"

# Paths that hold appstream metadata files
# the first one is the traditional one where most package reside but it is
# considered deprecated by upstream
# the other 3 are the ones used by upstream as noted in as-pool.c#L93-95
APPDATA_DATAPATHS="usr/share/appdata usr/share/app-info var/lib/app-info var/cache/app-info"

# Location where the cache files go when they are generated they are most
# of the time compressed with gvz extension
APPSTREAM_CACHE="var/cache/app-info/gv"

case "$ACTION" in
targets)
	echo "post-install post-remove"
	;;
run)
	case "$TARGET" in
	post-install|post-remove)
		if [ $PKGNAME = "AppStream" -a $TARGET = "post-remove" ]; then
			for f in ${APPSTREAM_CACHE}/*; do
				rm -f ${f}
			done
			echo "Removing AppStream cache..."
			rmdir ${APPSTREAM_CACHE}
			exit 0
		fi

		if [ ! -x "$APPSTREAMCLI" ]; then
			exit 0
		fi

		for path in ${APPDATA_DATAPATHS}; do
			APPSTREAM_PATHS="${APPSTREAM_PATHS} --datapath ${path}"
		done

		echo "Updating AppStream cache..."
		${APPSTREAMCLI} refresh-cache --force ${APPSTREAM_PATHS} --cachepath ${APPSTREAM_CACHE}
		;;
	esac
	;;
*)
	exit 1
	;;
esac

exit 0