#!/bin/sh
set -eu

package="${REMOTEHOST_CLI_PACKAGE:-@remotehost/cli}"
version="${REMOTEHOST_CLI_VERSION:-latest}"

say() {
  printf "%s\n" "$1"
}

fail() {
  printf "remotehost install failed: %s\n" "$1" >&2
  exit 1
}

command -v node >/dev/null 2>&1 || fail "Node.js 22 or newer is required. Install Node and rerun this command."
command -v npm >/dev/null 2>&1 || fail "npm is required. Install a Node.js distribution that includes npm."

node_major="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || true)"
if [ -z "$node_major" ] || [ "$node_major" -lt 22 ]; then
  fail "Node.js 22 or newer is required. Install Node 22+ and rerun this command."
fi

say "Installing the RemoteHost CLI"

if ! npm install --global "$package@$version"; then
  fail "npm could not install $package. If this was a permissions error, either fix your npm prefix (npm config set prefix ~/.npm-global) or install Node through a version manager."
fi

command -v remote >/dev/null 2>&1 || fail "installed, but 'remote' is not on your PATH. Add the directory printed by 'npm bin --global' to your PATH."

say "RemoteHost CLI installed: $(remote --version)"
say "Run: remote login"
