#!/bin/bash
set -e

# don't loop if files don't exist
shopt -s nullglob

mkdir -p tools/downloads
mkdir -p tools/cross/bin

if [[ ! -d builder/dist ]] ; then
    printf "This needs to be run from the root of the repo\n"
    exit 1
fi

# exit if TRAVIS_TAG is empty, no need to release anything
if [ -z "${TRAVIS_TAG}" ]; then
  exit 0
fi

if [[ ! -f "tools/downloads/linux-amd64-github-release.bz2" ]] ; then
  printf "Downloading tools/downloads/linux-amd64-github-release.bz2\n"
  curl -s -R -L -o "tools/downloads/linux-amd64-github-release.bz2" \
    "https://github.com/github-release/github-release/releases/download/v0.8.1/linux-amd64-github-release.bz2"
fi

bunzip2 "tools/downloads/linux-amd64-github-release.bz2"
mv "tools/downloads/linux-amd64-github-release" "tools/cross/bin/github-release"
chmod +x "tools/cross/bin/github-release"

export "PATH=$(pwd)/tools/cross/bin:$PATH"

# get user and repo names
USERNAME=$(echo ${TRAVIS_REPO_SLUG} | cut -d"/" -f1)
REPONAME=$(echo ${TRAVIS_REPO_SLUG} | cut -d"/" -f2)

# release
github-release release --user "${USERNAME}" --repo "${REPONAME}" --tag "${TRAVIS_TAG##*/}" --name "${TRAVIS_TAG##*/}" --description "$(cat builder/dist/release.md)"

# s6 overlay binaries
for i in builder/dist/*.tar.gz; do
  name=$(basename ${i})
  gpg -u 0x3B2FD161 --output "${i}.sig" --detach-sig "${i}"
  github-release upload --user "${USERNAME}" --repo "${REPONAME}" --tag "${TRAVIS_TAG##*/}" --name "${name}" --file "${i}"
  github-release upload --user "${USERNAME}" --repo "${REPONAME}" --tag "${TRAVIS_TAG##*/}" --name "${name}.sig" --file "${i}.sig"
done

# s6 overlay installer
for i in builder/dist/*-installer; do
  name=$(basename ${i})
  gpg -u 0x3B2FD161 --output "${i}.sig" --detach-sig "${i}"
  github-release upload --user "${USERNAME}" --repo "${REPONAME}" --tag "${TRAVIS_TAG##*/}" --name "${name}" --file "${i}"
  github-release upload --user "${USERNAME}" --repo "${REPONAME}" --tag "${TRAVIS_TAG##*/}" --name "${name}.sig" --file "${i}.sig"
done
