#!/bin/bash

set -ex

RELEASE_TAG=HEAD

while [ $# -gt 0 ]
do
  if [ "$1" == "--skip-checks" ]
  then
    skip_checks=true
  fi
  if [ "$1" == "--release-tag" ]
  then
    shift
    RELEASE_TAG=$1
  fi
  shift
done

if [ ! -e tools/make_release_tarball  -o  "$1" != "" ]
then
  echo "Handy script for creating tarball: Use from the checkout directory"
  exit 0
fi

set -e

VERSION=$(grep -E "project\(wlcs VERSION [[:digit:]]+(\.[[:digit:]]+)+\)" CMakeLists.txt | grep -E --only-matching "[[:digit:]]+(.[[:digit:]])+")

VERSIONED_NAME=wlcs-$VERSION

SCRATCH_DIR=$(mktemp -d)
BUILD_DIR=$(mktemp -d)
INSTALL_DIR=$(mktemp -d)

function cleanup() {
	ARG=$?
	[ -d $SCRATCH_DIR ] && rm -r $SCRATCH_DIR
	[ -d $BUILD_DIR ] && rm -r $BUILD_DIR
	[ -d $INSTALL_DIR ] && rm -r $INSTALL_DIR
	exit $ARG
}

trap cleanup EXIT

echo "Generating WLCS tarball…"
git archive --format=tar --prefix=$VERSIONED_NAME/ $RELEASE_TAG | xz -9 > $SCRATCH_DIR/$VERSIONED_NAME.tar.xz

if [ ! -v skip_checks ]
then
  (cd $SCRATCH_DIR; tar xvJf $SCRATCH_DIR/$VERSIONED_NAME.tar.xz)

  echo "Testing that the tarball is buildable"
  (cd $BUILD_DIR ; cmake $SCRATCH_DIR/$VERSIONED_NAME )
  make -C $BUILD_DIR -j $(nproc)

  echo "Testing that the tarball is installable"
  make -C $BUILD_DIR install DESTDIR=$INSTALL_DIR
fi

mv $SCRATCH_DIR/$VERSIONED_NAME.tar.xz .
echo "$VERSIONED_NAME.tar.xz successfully created and tested"

