#!/usr/bin/env bash

set -eu

# tests that the output of git status --porcelain is non-empty
if [ -n "$(git status --porcelain)" ]; then
    echo
    echo 'git status reports a working tree that is not pristine.'
    echo 'Please run this release script in a clean directory, such as after'
    echo
    echo '$ git clone'
    exit 1
fi

if [ -f VERSION ]; then
    echo 'Version number is:'
    echo
    cat VERSION
    echo
else
    echo "VERSION file doesn't exist; aborting release"
    exit 1
fi

release="./beluga-$(cat VERSION)"

echo 'Release directory name is:'
echo
echo "    ${release}"
echo

echo 'Building (native) in-tree first, for testing ...'
make clean
make || ( echo 'native make failed; aborting release.' ; exit 1 )

echo 'Running TEST (native) ...'
./TEST --examples || ( echo 'TEST failed; aborting release.' ; exit 1 )

if [ -e "${release}" ]; then
    echo "Release directory ${release} already exists."
    exit 1
fi

mkdir "${release}"

echo 'Copying files in root ...'
cp -a \
    INSTALL \
    AUTHORS \
    COPYRIGHT \
    LICENSE \
    VERSION \
    myocamlbuild.ml \
    Makefile \
    _tags \
    "${release}"

mkdir "${release}/bin"

# Set the RELEASE to true by default.
# sed -i 's/RELEASE *= *false/RELEASE = true/' $release

echo 'Copying src ...'
cp -a \
    src \
    "${release}"

echo 'Copying tools ...'
cp -a \
    tools \
    "${release}"

echo 'Copying examples ...'
cp -a \
    examples \
    "${release}"

(
    cd "${release}"
    echo "Deleting useless files:"
    useless=$(find . -print | grep -E '~|.DS_Store' || true)
    echo "rm -rf ${useless}"
    rm -rf "${useless}"

    # Remove examples not yet ready for public consumption
    echo "rm -rf examples/{notworking,cfg,beluga}"
    rm -rf examples/{notworking,cfg,beluga}

    echo "Copying ${release} to ${release-sandbox} ..."
)

release_sandbox="${release}-sandbox"

if [ -e "${release_sandbox}" ]; then
    echo "Release sandbox directory $release-sandbox already exists."
    exit 1
fi
cp -a "${release}" "${release_sandbox}"

(
    cd "${release_sandbox}"

    echo 'Building (native) in release directory ...'
    make clean
    make || ( echo 'native make failed; aborting release.' ; exit 1 )
)

echo "Leaving ${release_sandbox} around if you want to test further."

echo "Building archive ${release}.tar.gz"
tar zcf "${release}.tar.gz" "${release}" || ( echo 'tar failed.' ; exit 1 )
echo
ls -l "${release}.tar.gz"
echo
echo "Release built.  Don't forget to "'`'"git push' if needed."
