#!/bin/bash
# -*- mode: sh -*-

# orginal code copied from:
#   https://github.com/JasonEtco/upload-to-release/blob/master/upload-to-release

set -e
set -o pipefail

# Ensure that the GITHUB_TOKEN secret is included
if [[ -z "$GITHUB_TOKEN" ]]; then
  echo "Set the GITHUB_TOKEN env variable."
  exit 1
fi

# Only upload to non-draft releases
IS_DRAFT=$(jq --raw-output '.release.draft' $GITHUB_EVENT_PATH)
if [ "$IS_DRAFT" = true ]; then
  echo "This is a draft, so nothing to do!"
  exit 0
fi

# Build the Upload URL from the various pieces
RELEASE_ID=$(jq --raw-output '.release.id' $GITHUB_EVENT_PATH)
if [[ -z "${RELEASE_ID}" || "${RELEASE_ID}" = null ]]; then
  echo "There was no release ID in the GitHub event. Are you using the release event type?"
  exit 0
fi

for FILE in $(ls products); do
    # Prepare the headers
    AUTH_HEADER="Authorization: token ${GITHUB_TOKEN}"
    CONTENT_TYPE_HEADER="Content-Type: application/gzip"
    if [[ $(uname -s) == "Darwin" ]]; then
        CONTENT_LENGTH_HEADER="Content-Length: $(stat -f %z "products/${FILE}")"
    else
        CONTENT_LENGTH_HEADER="Content-Length: $(stat -c %s "products/${FILE}")"
    fi

    UPLOAD_URL="https://uploads.github.com/repos/${GITHUB_REPOSITORY}/releases/${RELEASE_ID}/assets?name=${FILE}"
    echo "$UPLOAD_URL"

    # Upload the file
    curl \
        -f \
        -sSL \
        -XPOST \
        -H "${AUTH_HEADER}" \
        -H "${CONTENT_LENGTH_HEADER}" \
        -H "${CONTENT_TYPE_HEADER}" \
        --upload-file "products/${FILE}" \
        "${UPLOAD_URL}"
done
