#!/bin/sh
# Installs the latest release of Maple.
#   curl -fsSL https://eu2.gateway.fivestats.org/install.sh | sh
set -eu

BASE="https://eu2.gateway.fivestats.org/releases"
VERSION="${VERSION:-0.4.2}"
PREFIX="${PREFIX:-/usr/local/bin}"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  aarch64 | arm64) arch=arm64 ;;
  *) echo "maple: unsupported architecture $(uname -m)" >&2; exit 1 ;;
esac
case "$os" in
  linux | darwin | freebsd) ;;
  *) echo "maple: unsupported operating system $os" >&2; exit 1 ;;
esac

name="maple-$VERSION-$os-$arch.tar.gz"
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

echo "Downloading Maple $VERSION for $os/$arch"
curl -fsSL -o "$tmp/$name" "$BASE/$VERSION/$name"
curl -fsSL -o "$tmp/SHA256SUMS" "$BASE/$VERSION/SHA256SUMS"
(cd "$tmp" && grep " $name\$" SHA256SUMS | sha256sum -c - >/dev/null)

tar -xzf "$tmp/$name" -C "$tmp" maple
if [ -w "$PREFIX" ]; then
  install -m 755 "$tmp/maple" "$PREFIX/maple"
else
  sudo install -m 755 "$tmp/maple" "$PREFIX/maple"
fi
echo "Installed $("$PREFIX/maple" --version)"
