#!/bin/sh

#
# Make a release of the latest tag, or of the tag/branch/commit specified as
# the first parameter.
#

PROJECT_NAME=$(basename "${PWD}")
PROJECT_VERSION=${1}
RELEASE_DIR="${PWD}/release"
KEY_ID=6237BAF1418A907DAA98EAA79C5EDD645A571EB2

mkdir -p "${RELEASE_DIR}"

if [ -z "${1}" ]; then
    # we take the last "tag" of the Git repository as version
    PROJECT_VERSION=$(git describe --abbrev=0 --tags)
    echo Version: "${PROJECT_VERSION}"
fi

if [ -f "${RELEASE_DIR}/${PROJECT_NAME}-${PROJECT_VERSION}.tar.xz" ]; then
    echo "Version ${PROJECT_VERSION} already has a release!"

    exit 1
fi

git archive --prefix "${PROJECT_NAME}-${PROJECT_VERSION}/" "${PROJECT_VERSION}" | tar -xf -

# We run "make vendor" in it to add all dependencies to the vendor directory 
# so we have a self contained source archive.
cd "${PROJECT_NAME}-${PROJECT_VERSION}" || exit 1
make vendor
cd ..
tar -cJf "${RELEASE_DIR}/${PROJECT_NAME}-${PROJECT_VERSION}.tar.xz" "${PROJECT_NAME}-${PROJECT_VERSION}"
rm -rf "${PROJECT_NAME}-${PROJECT_VERSION}"

# sign the release
gpg --default-key ${KEY_ID} --armor --detach-sign "${RELEASE_DIR}/${PROJECT_NAME}-${PROJECT_VERSION}.tar.xz"
minisign -Sm "${RELEASE_DIR}/${PROJECT_NAME}-${PROJECT_VERSION}.tar.xz"
