#!/usr/bin/env bash
set -eu

# This should be kept in sync with puppet/zulip/manifests/common.pp
version=2.8.0
arch="$(uname -m)"

case $arch in
    x86_64)
        tarball="tusd_linux_amd64"
        sha256=e13c8adc9bed4c993a72f60140f688736058d2c3f4a18fb6e59ca26e829fb93b
        ;;

    aarch64)
        tarball="tusd_linux_arm64"
        sha256=089eb6d144df7cc5e10ac611a18f407308aedb3f9024a78fa01cb60ba99005a9
        ;;
esac

check_version() {
    out="$(tusd --version)" && [[ "$out" = "Version: v$version
"* ]]
}

if ! check_version 2>/dev/null; then
    set -x
    tmpdir="$(mktemp -d)"
    trap 'rm -r "$tmpdir"' EXIT
    cd "$tmpdir"
    curl_opts=(-fLO --retry 3)
    curl "${curl_opts[@]}" "https://github.com/tus/tusd/releases/download/v${version}/${tarball}.tar.gz"
    sha256sum -c <<<"${sha256} ${tarball}.tar.gz"
    tar -xzf "${tarball}.tar.gz" --no-same-owner "${tarball}/tusd"
    install -Dm755 "${tarball}/tusd" /usr/local/bin/tusd
    check_version
fi
