#!/bin/sh

set -e

PLUGIN=$(grep ^Upstream-Name: debian/copyright | head -1 | cut -d' ' -f2)

GAJIM_COMPAT="master"
BRANCH_PREFIX=""
if test -n "$1"; then
    GAJIM_COMPAT="$1"
    BRANCH_PREFIX="gajim_"
fi

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

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 -czvf "$FILENAME" -C "$REPO"/ "$PLUGIN"/
echo You may remove "$TMPDIR" now
