#!/bin/bash

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 -v",  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.'

The script aborts if the work tree contains uncommited changes - to
guard against rolling a release after running the automated tests in a
dirty tree. 

eof
}

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

VERSION=$( cylc -v )
if [[ $VERSION = *-dirty ]]; then
    echo "The work tree is not clean: ABORTING" >&2
    exit 1
fi

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

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