#!/usr/bin/bash
#
# Create a tarball with cvmfsexec distributions (one for each RHEL-like distro)
# with the OSG config.
#
# By default this uses the latest tagged version of cvmfsexec and creates the
# tarball as "cvmfsexec-osg.tar.gz".  See --help for how to override that.
#

DEFAULT_FILENAME=cvmfsexec-osg.tar.gz

DISTROS=(rhel7-x86_64 rhel8-x86_64 rhel9-x86_64)

prog=${0##*/}

fail () {
    echo "$prog:" "$@" >&2
    exit 1
}

usage () {
    cat >&2 <<END
Usage: $prog [<options>] [<destfile>]"

Makes a tarball with cvmfsexec distributions with the OSG config.
The tarball will contain distributions for: ${DISTROS[*]}

    <destfile> is the path to the tarball file to create (default $DEFAULT_FILENAME)

    -b|--branch|--tag <git branch or tag>
                            the git branch/tag of the cvmfsexec repo to check out
                            if not specified, will use the newest tagged version

END
}

destfile=$DEFAULT_FILENAME
tag=
while [[ $1 ]]; do
    case $1 in
        -h|--help) usage; exit 0 ;;
        -b|--branch|--tag)
            if [[ $2 ]]; then
                tag=$2
                shift 2
            else
                echo >&2 "$1 requires an argument"
                usage
                exit 2
            fi
            ;;
        -*) echo >&2 "unknown option $1"; usage; exit 2 ;;
        *) destfile=$1; shift ;;
    esac
done


set -o nounset
set -e
PS4='+ $LINENO: '
#set -x

workdir=$(mktemp -d -t "$prog-XXXXXX")
trap 'rm -rf "$workdir"' EXIT
pushd "$workdir"

# Check out the whole original repo to get all the tags/branches.
# We'll create individual copies for each distro.

git clone --mirror https://github.com/cvmfs/cvmfsexec orig-repo.git || fail "Error downloading cvmfsexec from GitHub"
pushd orig-repo.git
if [[ -z $tag ]]; then
    ## Branch/tag not specified.  Check out latest tagged version.
    version_tags=$(git tag --list 'v*' | sort -V)
    # ^^ can't use "git tag --sort", it requires git 2.0+
    tag=$(tail -n 1 <<<"$version_tags")
    [[ -n $tag ]] || fail "Couldn't get latest tagged version"
fi
popd

mkdir cvmfsexec
cd cvmfsexec

for distro in ${DISTROS[*]}; do
    echo "Cloning cvmfsexec $tag for $distro"
    git clone -c advice.detachedHead=false -b "$tag" ../orig-repo.git "$distro"
    pushd "$distro"
    ./makedist -m $distro osg || fail "Couldn't get osg distribution for $distro"
    popd
done

rm -rf orig-repo.git
cd ..
tar --hard-dereference --exclude-vcs -czf cvmfsexec.tar.gz cvmfsexec/
rm -rf cvmfsexec || :

popd
mv "$workdir/cvmfsexec.tar.gz" "$destfile"

echo
echo "cvmfsexec $tag tarball created at $destfile"

# vim:et:sw=4:sts=4:ts=8
