#!/bin/sh
#
# supa (supa-cli) standalone-binary installer.
#
# This script is a TEMPLATE. `scripts/publish-s3-release.sh` renders it by
# replacing the __SUPA_*__ sentinels below and uploads the result to your S3
# bucket as `install.sh`. End users run:
#
#   curl -fsSL https://<your-bucket-or-cdn>/install.sh | sh
#
# It downloads the native single-executable (Node SEA) build for the user's
# OS/arch from S3, verifies its SHA-256, extracts it, and installs a launcher
# on PATH. No Node.js or npm required on the user's machine.
#
# Everything lives under $SUPA_HOME (default ~/.supa):
#   ~/.supa/lib      the native binary + its runtime assets
#   ~/.supa/bin      the `supa` launcher (added to PATH)
# The user's config/history/settings also live in ~/.supa and are left alone.
#
# Overridable environment variables (mostly for testing / pinning):
#   SUPA_BASE_URL   base URL to download from (default: baked-in value)
#   SUPA_VERSION    pin a specific version (default: from latest.json)
#   SUPA_HOME       install prefix (default: $HOME/.supa)
#   SUPA_CMD        installed command name (default: baked-in value)

set -eu

# --- Configuration (rewritten at publish time) -------------------------------
# Kept split so an un-rendered local copy fails loudly instead of silently
# downloading from a placeholder host.
supa_unconfigured_base_url="__SUPA_BASE""_URL__"
supa_base_url="${SUPA_BASE_URL:-https://supahifive-releases.s3.us-east-1.amazonaws.com/supa-cli}"
supa_base_url="${supa_base_url%/}"
supa_cmd="${SUPA_CMD:-supa}"
[ "$supa_cmd" = "__SUPA""_CMD__" ] && supa_cmd="supa"

supa_home="${SUPA_HOME:-$HOME/.supa}"
supa_lib="$supa_home/lib"
supa_bin="$supa_home/bin"

fail() {
	printf 'error: %s\n' "$1" >&2
	exit 1
}

need() {
	command -v "$1" >/dev/null 2>&1 || fail "'$1' is required but not found on PATH."
}

if [ "$supa_base_url" = "$supa_unconfigured_base_url" ] || [ -z "$supa_base_url" ]; then
	fail "installer download URL is not configured. Set SUPA_BASE_URL or use the published installer."
fi

need curl
need tar

# --- Detect platform ----------------------------------------------------------
os="$(uname -s)"
arch="$(uname -m)"

case "$os" in
	Darwin) os_id="darwin" ;;
	Linux)  os_id="linux" ;;
	*) fail "unsupported OS '$os'. Windows users: download supa-win32-x64.zip from $supa_base_url and add it to PATH manually." ;;
esac

case "$arch" in
	arm64|aarch64) arch_id="arm64" ;;
	x86_64|amd64)  arch_id="x64" ;;
	*) fail "unsupported architecture '$arch'." ;;
esac

platform="${os_id}-${arch_id}"

# The published SEA targets. Node SEA is host-only, so coverage depends on which
# platforms were built and uploaded for this release.
case "$platform" in
	darwin-arm64|darwin-x64|linux-x64|linux-arm64) ;;
	*) fail "no published binary for platform '$platform'." ;;
esac

# --- Resolve version ----------------------------------------------------------
version="${SUPA_VERSION:-}"
if [ -z "$version" ]; then
	printf 'Resolving latest version...\n'
	latest_json="$(curl -fsSL "$supa_base_url/latest.json")" || fail "could not fetch $supa_base_url/latest.json"
	version="$(printf '%s' "$latest_json" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"v\{0,1\}\([^"]*\)".*/\1/p' | head -1)"
	[ -n "$version" ] || fail "could not parse version from latest.json"
fi
version="${version#v}"

archive="supa-${platform}.tar.gz"
release_prefix="$supa_base_url/releases/v${version}"
archive_url="$release_prefix/$archive"
sums_url="$release_prefix/SHA256SUMS"

printf 'Installing %s v%s (%s)\n' "$supa_cmd" "$version" "$platform"

# --- Download + verify --------------------------------------------------------
tmp="$(mktemp -d "${TMPDIR:-/tmp}/supa.XXXXXX")" || fail "could not create temp dir"
trap 'rm -rf "$tmp"' EXIT INT TERM

printf 'Downloading %s...\n' "$archive"
curl -fsSL "$archive_url" -o "$tmp/$archive" || fail "download failed: $archive_url"

if curl -fsSL "$sums_url" -o "$tmp/SHA256SUMS" 2>/dev/null; then
	expected="$(sed -n "s/^\\([0-9a-f]\\{64\\}\\)[[:space:]]\\{1,\\}\\*\\{0,1\\}${archive}\$/\\1/p" "$tmp/SHA256SUMS" | head -1)"
	if [ -n "$expected" ]; then
		if command -v shasum >/dev/null 2>&1; then
			actual="$(shasum -a 256 "$tmp/$archive" | awk '{print $1}')"
		elif command -v sha256sum >/dev/null 2>&1; then
			actual="$(sha256sum "$tmp/$archive" | awk '{print $1}')"
		else
			actual=""
			printf 'warning: no sha256 tool found; skipping checksum verification.\n' >&2
		fi
		if [ -n "$actual" ] && [ "$actual" != "$expected" ]; then
			fail "checksum mismatch for $archive (expected $expected, got $actual)"
		fi
		[ -n "$actual" ] && printf 'Checksum verified.\n'
	else
		printf 'warning: %s not listed in SHA256SUMS; skipping verification.\n' "$archive" >&2
	fi
else
	printf 'warning: SHA256SUMS not found; skipping checksum verification.\n' >&2
fi

# --- Extract + install --------------------------------------------------------
printf 'Extracting...\n'
tar -xzf "$tmp/$archive" -C "$tmp"
# Archive root is a wrapper directory named "supa/" containing the executable
# plus its runtime assets.
[ -x "$tmp/supa/$supa_cmd" ] || fail "unexpected archive layout: $tmp/supa/$supa_cmd not found"

rm -rf "$supa_lib"
mkdir -p "$supa_lib" "$supa_bin"
cp -R "$tmp/supa/." "$supa_lib/"
chmod +x "$supa_lib/$supa_cmd"

# Launcher wrapper: exec the real binary from $supa_lib so its runtime asset
# lookups (relative to the executable) resolve correctly.
launcher="$supa_bin/$supa_cmd"
cat > "$launcher" <<EOF
#!/bin/sh
exec "$supa_lib/$supa_cmd" "\$@"
EOF
chmod +x "$launcher"

printf 'Installed to %s\n' "$supa_lib"

# --- PATH setup ---------------------------------------------------------------
case ":$PATH:" in
	*":$supa_bin:"*) on_path=1 ;;
	*) on_path=0 ;;
esac

if [ "$on_path" -eq 0 ]; then
	added=0
	for rc in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.profile"; do
		[ -e "$rc" ] || continue
		if ! grep -Fq "$supa_bin" "$rc" 2>/dev/null; then
			printf '\n# supa\nexport PATH="%s:$PATH"\n' "$supa_bin" >> "$rc"
			printf 'Added %s to PATH in %s\n' "$supa_bin" "$rc"
			added=1
		fi
	done
	if [ "$added" -eq 0 ]; then
		printf '\nAdd this to your shell profile:\n  export PATH="%s:$PATH"\n' "$supa_bin"
	fi
	printf '\nRestart your shell (or run: export PATH="%s:$PATH") then run: %s\n' "$supa_bin" "$supa_cmd"
else
	printf '\nRun: %s\n' "$supa_cmd"
fi

printf '\nDone. %s v%s is installed.\n' "$supa_cmd" "$version"
