#!/usr/bin/env sh
# Gerdoo CLI installer. Detects the platform, downloads the matching binary, and
# installs it to a bin directory on PATH. Intended to be served and piped:
#
#   curl -fsSL https://get.gerdoo.cloud/install.sh | sh
#
# Overridable via env:
#   GERDOO_CLI_BASE_URL  where the binaries live   (default below)
#   GERDOO_BIN_DIR       install location          (default /usr/local/bin)
#   GERDOO_VERSION       version subpath to fetch  (default "latest")
set -eu

BASE_URL="${GERDOO_CLI_BASE_URL:-https://get.gerdoo.cloud/cli}"
VERSION="${GERDOO_VERSION:-latest}"
BIN_DIR="${GERDOO_BIN_DIR:-/usr/local/bin}"

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$arch" in
	x86_64 | amd64) arch="amd64" ;;
	aarch64 | arm64) arch="arm64" ;;
	*) echo "gerdoo: unsupported architecture: $arch" >&2; exit 1 ;;
esac
case "$os" in
	linux | darwin) ;;
	*) echo "gerdoo: unsupported OS: $os (on Windows, download gerdoo_windows_amd64.exe)" >&2; exit 1 ;;
esac

file="gerdoo_${os}_${arch}"
url="${BASE_URL}/${VERSION}/${file}"

tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
echo "Downloading $url"
if ! curl -fSL "$url" -o "$tmp"; then
	echo "gerdoo: download failed from $url" >&2
	exit 1
fi
chmod +x "$tmp"

target="${BIN_DIR}/gerdoo"
if [ -w "$BIN_DIR" ]; then
	mv "$tmp" "$target"
else
	echo "Installing to $target (needs sudo)"
	sudo mv "$tmp" "$target"
fi
trap - EXIT

echo "Installed: $("$target" version)"
echo "Run 'gerdoo login' to get started."
