#!/bin/sh
# relay installer — fetch the relay client and put it on your PATH.
#
#   curl -fsSL https://<host>/setup.sh | sh
#
# Env overrides:
#   RELAY_URL          service URL (defaults to the host this script came from)
#   RELAY_INSTALL_DIR  install directory (default: first writable of the list below)
#   RELAY_BIN_NAME     installed command name (default: relay)

set -u

BASE_URL="https://relay.samyx.net"
BIN_NAME="${RELAY_BIN_NAME:-relay}"

_err() {
	printf 'relay-setup: %s\n' "$1" >&2
	exit 1
}

command -v curl >/dev/null 2>&1 || _err "curl is required but not found"

# The marker is split so serve-time substitution rewrites only the BASE_URL
# assignment above, not this comparison. If BASE_URL is still the placeholder
# (script run un-served), fall back to $RELAY_URL.
_ph='__RELAY''_DEFAULT_URL__'
[ "$BASE_URL" = "$_ph" ] && BASE_URL=""
[ -n "${RELAY_URL:-}" ] && BASE_URL="$RELAY_URL"
[ -n "$BASE_URL" ] || _err "no service URL; set RELAY_URL=https://<host> and re-run"

# Pick an install directory: prefer one that is writable AND already on PATH,
# then a writable ~/.local/bin or ~/bin (created if needed), then /usr/local/bin.
_in_path() {
	case ":${PATH:-}:" in
	*":$1:"*) return 0 ;;
	*) return 1 ;;
	esac
}

_choose_dir() {
	if [ -n "${RELAY_INSTALL_DIR:-}" ]; then
		printf '%s\n' "$RELAY_INSTALL_DIR"
		return
	fi
	for d in "$HOME/.local/bin" "$HOME/bin" /usr/local/bin; do
		if _in_path "$d" && [ -d "$d" ] && [ -w "$d" ]; then
			printf '%s\n' "$d"
			return
		fi
	done
	for d in "$HOME/.local/bin" "$HOME/bin"; do
		if mkdir -p "$d" 2>/dev/null && [ -w "$d" ]; then
			printf '%s\n' "$d"
			return
		fi
	done
	[ -w /usr/local/bin ] && {
		printf '%s\n' /usr/local/bin
		return
	}
	printf '%s\n' "$HOME/.local/bin"
}

INSTALL_DIR="$(_choose_dir)"
mkdir -p "$INSTALL_DIR" 2>/dev/null || _err "cannot create install directory: $INSTALL_DIR"
[ -w "$INSTALL_DIR" ] || _err "install directory not writable: $INSTALL_DIR (try RELAY_INSTALL_DIR=…)"

DEST="$INSTALL_DIR/$BIN_NAME"
TMP="$DEST.$$.tmp"

printf 'downloading relay client from %s ...\n' "$BASE_URL/relay.sh" >&2
curl -fsSL "$BASE_URL/relay.sh" -o "$TMP" || _err "download failed from $BASE_URL/relay.sh"

# Sanity check: make sure we actually got the client, not an error page.
if ! head -n 1 "$TMP" | grep -q '^#!/bin/sh'; then
	rm -f "$TMP"
	_err "downloaded file does not look like the relay client"
fi

chmod +x "$TMP"
mv -f "$TMP" "$DEST" || {
	rm -f "$TMP"
	_err "could not install to $DEST"
}

printf 'installed %s -> %s\n' "$BIN_NAME" "$DEST" >&2

if _in_path "$INSTALL_DIR"; then
	printf '\ndone. next:\n  %s config --user <your-username>\n  %s channel create --buffer --name box\n' "$BIN_NAME" "$BIN_NAME" >&2
else
	printf '\n%s is not on your PATH yet. Add it:\n  export PATH="%s:$PATH"\n(append that to ~/.profile, ~/.bashrc, or ~/.zshrc to make it permanent)\n\nthen:\n  %s config --user <your-username>\n' "$INSTALL_DIR" "$INSTALL_DIR" "$BIN_NAME" >&2
fi
