#!/bin/bash

# Set the current target version
export 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.
export SUFFIX=${SUFFIX:-"true"}

# Setting base path for tarballs. Tarballs for indivitual modules
# will be created into folders in same structure, as is in 'tde'.
# The default is 'tde-tarballs' in parent directory.
TARBALLS_BASE=${TARBALLS_BASE:-"$(dirname $PWD)/tde-tarballs"}

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 | \
    grep -v "common" | \
    while read submodule; do
        if [[ ! -e "$submodule/.git" ]]; then
            git submodule init -- "$submodule"
            git submodule update -- "$submodule"
        fi
        export TARBALL_DIR=$TARBALLS_BASE/$(dirname "$submodule")
        if [[ ! -d "$TARBALL_DIR" ]]; then
            mkdir -p "$TARBALL_DIR"
        fi
        (cd $submodule && $(dirname "$0")/create_tarball)
    done
fi
