#!/bin/bash

# Set the current target version
TARGET=${TARGET:-"14.0.0"}

# When $SUFFIX = true then the package tarball name will be $package-trinity.
# When $SUFFIX != true then the package tarball name will be trinity-$package.
# Choose the option that satisfies any distro package name rules.
SUFFIX=${SUFFIX:-"true"}

# Setting where the tarball will be created.
# The default is the parent directory (..).
TARBALL_DIR=${TARBALL_DIR:-".."}

if [[ ! -e .git ]] ||
   [[ -z "`git rev-parse --git-dir 2>/dev/null`" ]]; then
        echo "This script can only be run from a top level git directory.  Exiting..."
        exit 1
fi

branch=`git branch --contains HEAD | grep -v "no branch" | head -n1 | cut -c 3-`
if [[ -z "$branch" ]] ||
   [[ -z "`git rev-parse --symbolic-full-name --remotes=\"*/$branch\"`" ]]; then
        echo "There is not active upstream branch.  Exiting..."
        exit 1
fi

cd `git rev-parse --show-toplevel`
if [[ -e .gitmodules ]]; then
    sed -n "s|^\[submodule \"\([^\"]*\)\"\]$|\1|p" <.gitmodules | \
    while read submodule; do
        if [[ ! -e "$submodule/.git" ]]; then
            git submodule init -- "$submodule"
            git submodule update -- "$submodule"
        fi
    done
fi
if [[ ! -z "`git status --porcelain`" ]]; then
        echo "Current tree contains changes that have not been committed.  Exiting..."
        exit 1
fi
if [[ -z "`git branch -r --contains HEAD`" ]]; then
        echo "Current tree contains commits not pushed to the server.  Exiting..."
        exit 1
fi

tag=`git tag | sort -r | while read t; do \
     git branch --contains $t | cut -c 3- | grep -x "$branch" >/dev/null && \
     echo $t && break; done`
if [[ ! -z "$tag" ]]; then
    tag=$tag..HEAD
fi

count=`git log $tag --pretty=oneline | wc -l`

if [ "$SUFFIX" = "true" ]; then
    package=$(basename $PWD)-trinity-$TARGET
else
    package=trinity-$(basename $PWD)-$TARGET
fi
if [[ "$count" -gt 0 ]]; then
    package=$package~pre$count+$(git rev-parse HEAD | cut -c 1-8)
fi

echo "Package name: $package"
echo "Creating tarball in $TARBALL_DIR."
tar c  --exclude .git --exclude .gitmodules --transform "s|^\.|$package|" ./ | \
xz -9 >$TARBALL_DIR/$package.tar.xz
