#! /bin/sh

set -e

cleanup()
{
	make -C "$ORIGDIR/" clean -k || true
	make -C "$ORIGDIR/" distclean -k || true
	rm -rf "$ORIGDIR/bundles"
# TODO do something about globals/config.ml
	# remove some junk and autogenerated files
	find "$ORIGDIR/" -name .depend -print -exec rm "{}" \;
	find "$ORIGDIR/" -name .subdirs -print -exec rm "{}" \;
	find "$ORIGDIR/" -name \*.pyc -print -exec rm "{}" \;
}

if test ! $# = 1; then exit 1; fi

tarball="$1"
tmpdir="`mktemp -td repackXXXXXX`"

tar -C "$tmpdir" -xzf "$tarball"
ORIGDIR="`ls -d \"$tmpdir/coccinelle-\"*`"
archname="`basename \"$ORIGDIR\"`"

cleanup

# repack the source
GZIP=-9 tar -czC "$tmpdir" -f "result.tar.gz" "$archname"
rm -rf "$tmpdir"
