#!/bin/bash

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

set -e; trap "echo ERROR" ERR

function usage {
cat <<eof
USAGE: make-tarball

Roll an archive of the clean cylc source tree from the head of the
current repository branch.

The version string, from "cylc --version",  is generated by 'git describe'
which references (a) the latest annotated tag, (b) the number of commits
since the tag, and (c)the hash ID of the latest commit.

How to apply an annotated tag to the repository:
 % git tag -a x.y.z -m 'Official cylc-x.y.z release.'

eof
}

get_version() {
    CYLC_VERSION="$(python -c "from cylc.flow import __version__;\
        print(__version__)")"
}

for ARG in "$@"; do
    if [[ $ARG == '--help' || $ARG == "help" ]]; then
        usage
        exit 0
    fi
done

if [[ ! -d .git && ! -f .git ]]; then
    echo "This is not a cylc git repository: ABORTING" >&2
    exit 1
fi

get_version

RELEASE="cylc-${CYLC_VERSION}"
TARBALL=${RELEASE}.tar.gz
BRANCH=$( git rev-parse --abbrev-ref HEAD )

git archive "$BRANCH" --prefix="$RELEASE/" | gzip > "$TARBALL"
ls -lh "$TARBALL"
