#!/bin/sh
# Install Zetlyn, the binary for this machine from its latest release on GitHub.
#
#   curl -fsSL https://zetlyn.com/install.sh | sh
#
# It fetches one archive and its checksum, refuses the archive if they differ, and puts `zetlyn`
# in ~/.local/bin (or $ZETLYN_BIN). Nothing else: no sudo, no daemon, nothing that calls home.
# The source is https://github.com/zetlynhq/zetlyn and the documentation https://zetlyn.com/docs.
set -eu

REPO=zetlynhq/zetlyn
case "$(uname -s)-$(uname -m)" in
	Darwin-arm64) TARGET=macos-arm64 ;;
	Darwin-x86_64) TARGET=macos-x86_64 ;;
	Linux-x86_64 | Linux-amd64) TARGET=linux-x86_64 ;;
	*)
		echo "There is no binary for $(uname -s) $(uname -m) yet. With Rust 1.80 or later:" >&2
		echo "  cargo install --git https://github.com/$REPO" >&2
		exit 1
		;;
esac

BIN=${ZETLYN_BIN:-$HOME/.local/bin}
URL=https://github.com/$REPO/releases/latest/download
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

echo "Fetching zetlyn for $TARGET"
curl -fsSL "$URL/zetlyn-$TARGET.tar.gz" -o "$TMP/zetlyn.tar.gz"
curl -fsSL "$URL/SHA256SUMS" -o "$TMP/SHA256SUMS"
want=$(grep " zetlyn-$TARGET.tar.gz\$" "$TMP/SHA256SUMS" | cut -d' ' -f1)
if command -v shasum >/dev/null 2>&1; then
	have=$(shasum -a 256 "$TMP/zetlyn.tar.gz" | cut -d' ' -f1)
else
	have=$(sha256sum "$TMP/zetlyn.tar.gz" | cut -d' ' -f1)
fi
if [ -z "$want" ] || [ "$want" != "$have" ]; then
	echo "The download does not match its checksum, so nothing was installed." >&2
	exit 1
fi

tar -xzf "$TMP/zetlyn.tar.gz" -C "$TMP"
mkdir -p "$BIN"
cp "$TMP/zetlyn" "$BIN/zetlyn"
chmod 0755 "$BIN/zetlyn"
echo "Installed: $BIN/zetlyn ($("$BIN/zetlyn" --version))"
case ":$PATH:" in
	*":$BIN:"*) ;;
	*) echo "Add it to your PATH:  export PATH=\"$BIN:\$PATH\"" ;;
esac
echo "Then run:  zetlyn"
