#!/bin/sh

set -e

test -n "$1" || (
    echo "call $0 upstream-plugin-dir gajim-compat-version"
    echo "e.g. $0 anti_spam 1.1"
)
PLUGIN="$1"
test -n "$2"
GAJIM_COMPAT="$2"

REPO=gajim-plugins
PACKAGE=gajim-$(echo "$PLUGIN" | sed 's/_//g')
EXCLUDE=--exclude=qrcodewin

BRANCH_PREFIX="gajim_"
if [ "$GAJIM_COMPAT" = "master" ]; then
    BRANCH_PREFIX=""
fi

CWD=$(pwd)
TMPDIR=$(mktemp -d)
cd "$TMPDIR"
git clone https://dev.gajim.org/gajim/"$REPO".git
( cd ./"$REPO"/ &&
  git checkout "$BRANCH_PREFIX$GAJIM_COMPAT" )
( cd ./"$REPO"/"$PLUGIN"/ &&
  dos2unix $(find . -name "*.py" -o -name "*.json" -o -name "*.ui" \
             -o -name "*.md" -o -name COPYING -o -name CHANGELOG) )
VERSION=$(python3 -c 'import json, sys; print(json.load(sys.stdin)["version"])' \
		  < ./"$REPO"/"$PLUGIN"/plugin-manifest.json)
FILENAME="$CWD"/../"$PACKAGE"_"$VERSION".orig.tar.gz
test ! -e "$FILENAME"
tar $EXCLUDE -czvf "$FILENAME" -C "$REPO"/ "$PLUGIN"/
echo You may remove "$TMPDIR" now
