#!/bin/sh
# Install the latest ushr release binaries — no Go toolchain, no checkout.
#
#   curl -fsSL https://get.ushr.io | sh
#
# While the repo is private, set GITHUB_TOKEN to a token with repo read access.
# Override the install dir with USHR_PREFIX (default ~/.local/bin).
set -eu

REPO="paddo-tech/ushr"
PREFIX="${USHR_PREFIX:-$HOME/.local/bin}"

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

gh_curl() {
	if [ -n "${GITHUB_TOKEN:-}" ]; then
		curl -fsSL -H "Authorization: Bearer $GITHUB_TOKEN" "$@"
	else
		curl -fsSL "$@"
	fi
}

echo "==> Finding latest release"
json=$(gh_curl "https://api.github.com/repos/$REPO/releases/latest") || {
	echo "!! Could not read releases for $REPO." >&2
	echo "   Private repo? export GITHUB_TOKEN=<token with repo read> and re-run." >&2
	exit 1
}
tag=$(printf '%s\n' "$json" | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -1)
name="ushr_${tag#v}_${os}_${arch}.tar.gz"
# Asset objects list "id" before "name"; remember the last id seen and emit it
# when the wanted name matches. Downloading by asset id (octet-stream) is the
# form that also works on private repos.
asset_id=$(printf '%s\n' "$json" | awk -v name="$name" '
	/"id":/ { id=$2; gsub(/[^0-9]/, "", id) }
	index($0, "\"name\": \"" name "\"") { print id; exit }')
if [ -z "$asset_id" ]; then
	echo "!! No asset $name in release $tag." >&2
	exit 1
fi

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
echo "==> Downloading ushr $tag ($os/$arch)"
gh_curl -H "Accept: application/octet-stream" \
	-o "$tmp/ushr.tar.gz" "https://api.github.com/repos/$REPO/releases/assets/$asset_id"
tar -xzf "$tmp/ushr.tar.gz" -C "$tmp"

mkdir -p "$PREFIX"
for bin in ushr ushr-agent ushr-controller; do
	install -m 755 "$tmp/$bin" "$PREFIX/$bin"
done
echo "==> Installed ushr $tag to $PREFIX"

case ":$PATH:" in
	*":$PREFIX:"*) ;;
	*) echo "!! Add $PREFIX to your PATH." ;;
esac

cat <<EOF

Next — one command:

  ushr login                 # hosted plane: guided setup end to end
  ushr setup --org YOUR_ORG  # local/OSS: GitHub App + local services
EOF
