#!/bin/bash

set -x

SRC_VERSION=$1
TARBALL=$2

if echo ${SRC_VERSION} | grep -q git; then
        GIT_COMMIT=$( echo ${SRC_VERSION} | awk -F"+" '{ print $2 }' | sed 's/git//' )
        UPSTREAM="https://github.com/spotweb/spotweb.git"
else
        GIT_TAG=v$( echo ${SRC_VERSION} | awk -F"+" '{ print $1 }' | sed 's/0~//' )
        UPSTREAM_URL="https://github.com/spotweb/spotweb/tarball/$GIT_TAG"
fi

TMPDIR=$( mktemp --tmpdir -d spotweb.XXXXXX ) || exit 1
DESTDIR="$TMPDIR/spotweb"

if [ -z $GIT_COMMIT ]; then
        UPSTREAM_TARBALL="$TMPDIR/spotweb.tar.gz"

        echo "Fetching upstream source from $UPSTREAM_URL"
        wget -O "$UPSTREAM_TARBALL" "$UPSTREAM_URL"

        mkdir "$DESTDIR"
        tar xzf "$UPSTREAM_TARBALL" --strip-components=1 -C "$DESTDIR" 
else
        # Clone the upstream source
        echo "Cloning git repository $UPSTREAM into $DESTDIR"
        git clone --quiet "$UPSTREAM" "$DESTDIR"
fi

# Change into the source directory
pushd "$DESTDIR"

if [ ! -z $GIT_COMMIT ]; then
        # Check out the proper commit
        echo "Checking out git commit $GIT_COMMIT"
        git checkout --quiet "$GIT_COMMIT"

        # Remove the .git directory
        rm -rf ".git"
fi

echo "Cleaning up upstream source"

# Remove the css and js files that will be replaced by versions from the
# proper Debian package

rm "templates/we1rdo/css/jquery-ui-1.8.13.custom.css"
rm "js/jquery/jquery.min.js"
rm "js/jquery/jquery.cookie.js"
rm "js/fancybox/jquery.easing-1.3.pack.js"
rm "js/fancybox/jquery.mousewheel-3.0.4.pack.js"

# Remove notifo notifications: the notifo library is nonfree
# and the service has been discontinued
rm -r "lib/notifications/notifo"
rm "lib/notifications/Notifications_Notifo.php"
sed -i -e "/notifo/d" lib/notifications/Notifications_Factory.php

# Remove the bundled Net::NNTP library, which is also in
# the php-net-nntp package

rm -r NNTP

# Then, remove packed css and js files
# We're removing them all to make sure we don't miss any
find . \( -name \*pack.css -o -name \*min.css \
    -o -name \*pack.js -o -name \*min.js \) -a -exec rm "{}" \;

# Remove git stuff
rm .gitignore
rm .gitattributes

popd

echo "Creating orig tarball $TARBALL"
tar czf "$TARBALL" -C "$TMPDIR" spotweb

echo "Cleaning up $TMPDIR"
rm -rf "$TMPDIR"

