#!/bin/bash
set -uo pipefail
trap 's=$?; echo ": Error on line "$LINENO": $BASH_COMMAND"; exit $s' ERR
IFS=$'\n\t'

error() {
    # is stderr a tty?
    if [ -t 2 ]; then
        ERRORFMT='\e[1;31;91m%s\e[0m\n'
    else
        ERRORFMT='%s\n'
    fi
    printf "$ERRORFMT" "$1" >&2
    exit "${2:-1}"
}

unset WORKDIR
workdir() {
    if [ -z "${WORKDIR:+x}" ]; then
        # if a temporary working directory hasn't been established, create one
        TMPDIR="${TMPDIR:-$(dirname $(mktemp -u))}"
        WORKDIR=$(mktemp -d "$TMPDIR/.$(basename "$0").XXXXXXXXXX")
        # it's polite to clean up after ourselves
        trap "rm -rf \"$WORKDIR\"" INT EXIT
    fi
}

workdir

BASE=https://ryanc-musl-bins.s3.amazonaws.com

# architecture is the first argument, the rest are binary names
ARGS=("$@")
ARCH="${ARGS[0]}"
BINS=("${ARGS[@]:1}")

# detect which compression format to use, xz is preferred because it's smaller
if command -v unxz > /dev/null; then
    FORMAT=xz
    UNPACK=unxz
elif command -v xzdec > /dev/null; then
    FORMAT=xz
    UNPACK=xzdec
else
    FORMAT=gz
    UNPACK=gunzip
fi

# download SHA256SUMS and its signature file
for NAME in SHA256SUMS SHA256SUMS.minisig; do
    curl -so "$WORKDIR/$NAME" "$BASE/$NAME"
done

# verify the SHA256SUMS file
PUB="RWQwnv+4l4uv60kab+K2sjXkATMVxetuVUvaCuBX2XXTIOqziTvbXk3N"
if command -v rsign > /dev/null; then
    rsign verify -qP "$PUB" "$WORKDIR/SHA256SUMS"
elif command -v minisign > /dev/null; then
    minisign -V -qP "$PUB" -m "$WORKDIR/SHA256SUMS"
elif command -v miniverify > /dev/null; then
    miniverify -V -qP "$PUB" -m "$WORKDIR/SHA256SUMS"
else
    echo "No compatible signature verification tool!"
    exit 1
fi

# download compressed binaries
for BIN in "${BINS[@]}"; do
    mkdir -p "$WORKDIR/$ARCH"
    curl -so "$WORKDIR/$ARCH/$BIN.$FORMAT" "$BASE/$ARCH/$BIN.$FORMAT"
done

pushd "$WORKDIR" > /dev/null

# *quietly* verify compressed binaries
sha256sum --ignore-missing -c --quiet SHA256SUMS || \
error "compressed hash validation failed"

for BIN in "${BINS[@]}"; do
    $UNPACK -dc "$WORKDIR/$ARCH/$BIN.$FORMAT" > "$WORKDIR/$ARCH/$BIN"
    rm "$WORKDIR/$ARCH/$BIN.$FORMAT"
    chmod +x "$WORKDIR/$ARCH/$BIN"
done

# verify decompresssed binaries
sha256sum --ignore-missing -c SHA256SUMS || \
error "hash validation failed"

popd > /dev/null

# move binaries from the workdir to the current directory
for BIN in "${BINS[@]}"; do
    mv "$WORKDIR/$ARCH/$BIN" .
done
