#!/bin/bash

# Set the current target version
# The default is the version detected from TDE core header.
export TARGET=${TARGET:-}

# 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:-}

# List of modules to be omitted during creating tarballs.
SKIP_MODULES="
common/admin
common/libltdl
common/libtdevnc
common/other
defaultsettins
experimental
infrastructure
metapackages
scripts
tde-construct
thirdparty
"
skip_module() {
  for skip in $SKIP_MODULES; do
    [ "/${1/$skip//}/" != "/$1/" ] && return 0
  done
  return 1
}

# echo in bold
echobd () {
    if [ -p /dev/stdout ]; then
        echo "$1"
    else
        echo -ne "\033[1m"
        echo -n "$1"
        echo -e "\033[0m"
    fi
}

# Move to main tde folder
REMOTE_URL=$(git config --get remote.origin.url 2>/dev/null)
if [ "$REMOTE_URL" != "${REMOTE_URL%/tde-packaging}" ]; then
    # Switch from tde-packaging into main tde folder
    cd `git rev-parse --show-toplevel`
    cd ../tde
    REMOTE_URL=$(git config --get remote.origin.url 2>/dev/null)
fi
while [ -n "$REMOTE_URL" ] && [ "$REMOTE_URL" = "${REMOTE_URL%/tde}" ]; do
    # Switch from submodule to parent
    cd `git rev-parse --show-toplevel`
    cd ..
    REMOTE_URL=$(git config --get remote.origin.url 2>/dev/null)
done
if [ "$REMOTE_URL" = "${REMOTE_URL%/tde}" ]; then
    # Main tde folder not found
    echo "This script can only be run from TDE git directory. Exiting."
    exit 1
fi
cd `git rev-parse --show-toplevel`

# Check remote branch
branch=`git symbolic-ref -q HEAD | sed "s|^refs/heads/||"`
if [[ -z "$branch" ]]; then
    branch_detached=`git branch --contains HEAD | egrep "^\* \(HEAD detached at" | head -n1 | sed "s|^\* (HEAD detached at \([^)]*\)).*$|\1|"`
    branch=`git tag | grep -Fx "${branch_detached}"`
fi
if [[ -z "$branch" ]]; then
    branch=`git branch -r --contains HEAD | egrep -v "no branch|detached" | head -n1 | cut -c 3-`
    branch=${branch#origin/}
fi
if [[ -z "$branch" ]] ||
   ( [[ -z "`git rev-parse --symbolic-full-name --remotes=\"*/$branch\"`" ]] &&
     [[ -z "`git tag | grep -Fx \"${branch}\"`" ]] ); then
    echo "There is not active upstream branch. Exiting."
    exit 1
fi

# Set target version
if [ -z "$TARGET" ]; then
    if [ -f main/dependencies/tde-cmake/modules/TDEVersion.cmake ]; then
        tdeversionHeader=main/dependencies/tde-cmake/modules/TDEVersion.cmake
    elif [ -f main/core/tdelibs/tdecore/tdeversion.h ]; then
        tdeversionHeader=main/core/tdelibs/tdecore/tdeversion.h
    elif [ -f main/core/tdelibs/kdecore/kdeversion.h ]; then
        tdeversionHeader=main/core/tdelibs/kdecore/kdeversion.h
    elif [ -f main/tdelibs/tdecore/tdeversion.h ]; then
        tdeversionHeader=main/tdelibs/tdecore/tdeversion.h
    elif [ -f main/tdelibs/kdecore/kdeversion.h ]; then
        tdeversionHeader=main/tdelibs/kdecore/kdeversion.h
    fi
    if [ -z "$tdeversionHeader" ]; then
        echo "Cannot find TDE core headers. Exiting."
        exit 1
    fi
    TARGET=`sed -n 's/^[ \t]*\(set( DEFAULT_VERSION\|#define [KT]DE_VERSION_STRING\) "[^0-9]\?\([^ ~"]*\).*/\2/p' $tdeversionHeader`
fi
export TARGET

# Check branch by target
if [ "$TARGET" != "${TARGET#3.5.}" ]; then
    if [ "$TARGET" != "${TARGET#3.5.13.}" ]; then
        targetBranch=v3.5.13-sru
    else
        targetBranch=master
    fi
    if [ "$branch" = "v${TARGET}" ]; then
        targetBranch=v${TARGET}
    fi
else
    if [ "$TARGET" != "${TARGET%.0}" ]; then
        targetBranch=master
    else
        targetBranch=r${TARGET%.*}.x
    fi
    if [ "$branch" = "r${TARGET}" ]; then
        targetBranch=r${TARGET}
    fi
fi
if [ "$branch" != "$targetBranch" ]; then
    echo "Target $TARGET is not valid on $branch branch. Exiting."
    exit 1
fi

# Setting base path for tarballs
TARBALLS_BASE=${TARBALLS_BASE:-"$(dirname $PWD)/tde-tarballs/$TARGET"}

# Create tarballs for submodules
echobd "Create tarballs for $(basename "$PWD") $branch branch"
echobd "Working in $PWD"
if [[ -e .gitmodules ]]; then
    create_tarball=$(dirname $(readlink -f "$0"))/create_tarball
    sed -n "s|^\[submodule \"\([^\"]*\)\"\]$|\1|p" <.gitmodules | \
    while read submodule; do
        skip_module "$submodule" && continue
        echobd "Module ${submodule}"
        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" && "$create_tarball")
    done
fi
echobd "Done in $PWD"