#!/bin/sh

set -e

. debian/scripts/plugin-functions.sh

if [ "$#" -ge 1 ]; then
	PLUGINS="$@"
else
	PLUGINS="$(get_plugins)"
fi

PREFIX="${USCAN_DESTDIR:-..}/$(get_orig_prefix)"
for plugin in $PLUGINS; do
	DIR="$(get_plugin_dir "$plugin")"
	VERSION="$(get_plugin_field "$plugin" Version)"
	ARCHIVE=
	for ext in .tar.xz .tar.bz2 .tar.gz; do
		if [ -f "$PREFIX-$DIR$ext" ]; then
			ARCHIVE="$PREFIX-$DIR$ext"
			break
		fi
	done
	if [ -z "$ARCHIVE" ]; then
		echo "Unable to find an archive for $plugin." >&2
		exit 1
	fi
	git rm -rq --ignore-unmatch "$DIR"
	mkdir -p "$DIR"
	tar -C "$DIR" --strip-components=1 -axf "$ARCHIVE"
    git add -- "$DIR"
    if ! git diff --quiet --cached -- "$DIR"; then
        git commit -m "Update $plugin to version $VERSION" -- "$DIR"
    fi
done
