#!/bin/sh
# Installs the `peep` CLI from https://dev.peepvibes.live/.
# Supported: Linux x86_64/aarch64 (static musl), macOS arm64/x86_64.
# Verifies the SHA-256 checksum before installing. Uninstall: remove the
# binary and ~/.config/peep (see README.md).
set -eu

BASE_URL="${PEEP_DOWNLOAD_BASE:-https://dev.peepvibes.live/download}"
INSTALL_DIR="${PEEP_INSTALL_DIR:-$HOME/.local/bin}"

case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=macos ;;
  *) echo "peep: unsupported OS $(uname -s) (supported: Linux, macOS)" >&2; exit 1 ;;
esac

case "$(uname -m)" in
  x86_64 | amd64) arch=x86_64 ;;
  aarch64 | arm64) arch=aarch64 ;;
  *) echo "peep: unsupported architecture $(uname -m)" >&2; exit 1 ;;
esac

name="peep-$os-$arch"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT INT TERM

echo "Downloading ${name}..."
curl -fsSL "$BASE_URL/$name.tar.gz" -o "$tmp/$name.tar.gz"
curl -fsSL "$BASE_URL/$name.tar.gz.sha256" -o "$tmp/$name.tar.gz.sha256"

cd "$tmp"
if command -v sha256sum >/dev/null 2>&1; then
  sha256sum -c "$name.tar.gz.sha256" >/dev/null
else
  shasum -a 256 -c "$name.tar.gz.sha256" >/dev/null
fi
echo "Checksum verified."

tar -xzf "$name.tar.gz"
mkdir -p "$INSTALL_DIR"
install -m 0755 "$name/peep" "$INSTALL_DIR/peep"

echo "Installed $INSTALL_DIR/peep ($("$INSTALL_DIR/peep" --version))"
case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *) echo "Add $INSTALL_DIR to your PATH." ;;
esac
echo "Next: peep login && peep --title \"trying an idea\""
