#!/usr/bin/env sh
# Deplomo 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.deplomo.com/install.sh | sh
#
# Overridable via env:
#   DEPLOMO_CLI_BASE_URL  where the binaries live   (default below)
#   DEPLOMO_BIN_DIR       install location          (default /usr/local/bin)
#   DEPLOMO_VERSION       version subpath to fetch  (default "latest")
set -eu

BASE_URL="${DEPLOMO_CLI_BASE_URL:-https://get.deplomo.com/cli}"
VERSION="${DEPLOMO_VERSION:-latest}"
BIN_DIR="${DEPLOMO_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 "deplomo: unsupported architecture: $arch" >&2; exit 1 ;;
esac
case "$os" in
	linux | darwin) ;;
	*) echo "deplomo: unsupported OS: $os (on Windows, download deplomo_windows_amd64.exe)" >&2; exit 1 ;;
esac

file="deplomo_${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 "deplomo: download failed from $url" >&2
	exit 1
fi
chmod +x "$tmp"

# sudo from a `curl | sh` pipe cannot read the password on stdin (that's the
# script). Re-open the controlling terminal so the prompt still works.
as_root() {
	if [ -r /dev/tty ]; then
		sudo "$@" </dev/tty
	else
		sudo "$@"
	fi
}

needs_root() {
	[ ! -d "$BIN_DIR" ] && return 0
	[ ! -w "$BIN_DIR" ] && return 0
	[ -e "$1" ] && [ ! -w "$1" ] && return 0
	return 1
}

target="${BIN_DIR}/deplomo"
if needs_root "$target"; then
	echo "Installing to $target (needs sudo)"
	if [ ! -d "$BIN_DIR" ]; then
		as_root mkdir -p "$BIN_DIR"
	fi
	as_root install -m 755 "$tmp" "$target"
else
	install -m 755 "$tmp" "$target"
fi
trap - EXIT
rm -f "$tmp"

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