#!/bin/bash

# Some notes:
#
# 1. This script is implemented using glab(1), which is pretty buggy in my
#    experience but a lot easier than deriving formulating API HTTP calls with
#    wget(1) or curl(1).
#
# 2. AFAICT, a “permanent link” [1] is not needed. glab(1) uploads to a
#    reasonable URL by default.
#
# 3. I did not find any way to specify a URL for the tarball. Both the “url”
#    and “direct_asset_path” of --asset-links seemed to be ignored, or
#    possibly that flag has no effect at all (remember how I said glab(1) was
#    buggy?).
#
# [1]: https://docs.gitlab.com/user/project/releases/release_fields/#permanent-links-to-release-assets


set -E

INFO () {
    echo "💅  $1" 1>&2
}

FATAL () {
    echo "☠️  ${1:-command failed lol}" 1>&2
    exit 1
}
trap FATAL ERR

if [ -z "$1" ] || [ "$1" = --help ]; then
    cat <<'EOF' 1>&2
Upload a release tarball to the Charliecloud packages repository using wget(1).

Usage:

  $ misc/tar-upload.sh VERSION
EOF
    exit 1
fi

version=$1
INFO "version: $version"
release="v$1"
INFO "release: $release"

tarball=charliecloud-$version.tar.gz
INFO "tarball: $tarball"
INFO " SHA256: $(sha256sum "$tarball" | cut -f1 -d' ')"

[[ -f "$tarball" ]] || FATAL 'tarball does not exist'

INFO 'validating GitLab.com login'
INFO 'note: “! Invalid token provided in configuration file” is OK'

glab auth status || FATAL 'no valid login, did you “glab auth login”?'

INFO "checking for release $release"
if ! release_text=$(glab release view "$release"); then
    FATAL "release not found: $release"
fi
echo "$release_text" | head -3

INFO "uploading tarball"
glab release upload "$release" "$tarball"
