#!/bin/sh -e

if [ "$#" -eq 0 ]; then
  printf "%s\n" "Usage: $(basename "$0") <user/repo>"
  exit 1
fi
repo="$1"

detect_platform() {
  platform="$(uname -s | tr '[:upper:]' '[:lower:]')"

  # check for MUSL
  if [ "${platform}" = "linux" ]; then
    if ldd /bin/sh | grep -i musl >/dev/null; then
      platform=unknown-linux-musl
    fi
  fi

  # mingw is Git-Bash
  if echo "${platform}" | grep -i mingw >/dev/null; then
    platform=pc-windows-msvc
  fi

  if [ "${platform}" = "linux" ]; then
    platform=unknown-linux-gnu
  fi

  if [ "${platform}" = "darwin" ]; then
    platform=apple-darwin
  fi

  echo "${platform}"
}

detect_arch() {
  arch="$(uname -m | tr '[:upper:]' '[:lower:]')"
  # `uname -m` in some cases mis-reports 32-bit OS as 64-bit
  # shellcheck disable=SC2312
  if [ "${arch}" = "x64" ] && [ "$(getconf LONG_BIT)" -eq 32 ]; then
    arch=i386
  fi
  echo "${arch}"
}

platform=$(detect_platform)
arch=$(detect_arch)

curl -sS "https://api.github.com/repos/${repo}/releases/latest" \
  | grep browser_download_url \
  | cut -d'"' -f4 \
  | grep "${platform}" \
  | grep "${arch}" \
  | fzf --multi \
  | xargs -I{} curl -LO --proto-redir -all,https {}
