#!/usr/bin/env bash
# Install asdf (https://asdf-vm.com) from the latest GitHub release.
#
# Usage:
#   ./install-asdf.sh              # latest, installs to ~/.local/bin
#   ./install-asdf.sh v0.20.0      # specific version
#   INSTALL_DIR=/usr/local/bin ./install-asdf.sh
set -euo pipefail

REPO="asdf-vm/asdf"
VERSION="${1:-latest}"
INSTALL_DIR="${INSTALL_DIR:-$HOME/.local/bin}"

need() { command -v "$1" >/dev/null 2>&1 || { echo "error: '$1' is required" >&2; exit 1; }; }
need curl
need tar
need install

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
case "$(uname -m)" in
  x86_64 | amd64) arch="amd64" ;;
  aarch64 | arm64) arch="arm64" ;;
  386 | i386 | i686) arch="386" ;;
  *) echo "error: unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

case "$os" in
  linux | darwin) ;;
  *) echo "error: unsupported OS: $os" >&2; exit 1 ;;
esac

if [ "$VERSION" = "latest" ]; then
  VERSION="$(curl -fsSLI -o /dev/null -w '%{url_effective}' \
    "https://github.com/$REPO/releases/latest" | sed -E 's#.*/tag/##')"
  case "$VERSION" in
    v[0-9]*) ;;
    *) echo "error: could not determine latest version" >&2; exit 1 ;;
  esac
fi

name="asdf-${VERSION}-${os}-${arch}"
base="https://github.com/$REPO/releases/download/$VERSION/$name.tar.gz"

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

echo "Downloading $name ..."
curl -fsSL -o "$tmp/asdf.tar.gz" "$base"
curl -fsSL -o "$tmp/asdf.md5" "$base.md5"

expected="$(tr -d '[:space:]' < "$tmp/asdf.md5")"
if command -v md5sum >/dev/null 2>&1; then
  actual="$(md5sum "$tmp/asdf.tar.gz" | cut -d' ' -f1)"
else
  actual="$(md5 -q "$tmp/asdf.tar.gz")"
fi
if [ "$expected" != "$actual" ]; then
  echo "error: checksum mismatch" >&2
  echo "  expected $expected" >&2
  echo "  got      $actual" >&2
  exit 1
fi

tar -xzf "$tmp/asdf.tar.gz" -C "$tmp"
mkdir -p "$INSTALL_DIR"
install -m755 "$tmp/asdf" "$INSTALL_DIR/asdf"

echo "Installed asdf $VERSION -> $INSTALL_DIR/asdf"
"$INSTALL_DIR/asdf" --version

case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *)
    echo
    echo "note: $INSTALL_DIR is not on your PATH. Add it, e.g.:"
    echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
    ;;
esac
