#!/usr/bin/env bash
# Pluma installer. Detects OS + arch, fetches the latest release
# tarball from GitHub, verifies its sha256, extracts to the current
# directory. Posted at https://plumachat.app/install.sh; the docs
# site is built from docs/ and this file ships as a static asset.
#
# Usage:
#   curl -fsSL https://plumachat.app/install.sh | bash
#
# Skeptical (recommended): read the script first, then run it.
#   curl -fsSL https://plumachat.app/install.sh -o /tmp/pluma-install.sh
#   less /tmp/pluma-install.sh
#   bash /tmp/pluma-install.sh
set -euo pipefail

repo="guygrigsby/pluma"

# Detect OS.
case "$(uname -s)" in
  Darwin) os="darwin" ;;
  Linux)  os="linux"  ;;
  *) echo "pluma installer: unsupported OS $(uname -s). Windows users grab the .zip from https://github.com/${repo}/releases/latest" >&2; exit 1 ;;
esac

# Detect arch.
case "$(uname -m)" in
  arm64|aarch64) arch="arm64" ;;
  x86_64|amd64)  arch="amd64" ;;
  *) echo "pluma installer: unsupported arch $(uname -m)." >&2; exit 1 ;;
esac

# macOS Intel binaries are uploaded under amd64. Linux ARM is not yet built;
# nudge the user toward the manual path so they're not stuck silently.
if [[ "$os" == "linux" && "$arch" == "arm64" ]]; then
  echo "pluma installer: linux-arm64 isn't published yet. Build from source: https://github.com/${repo}#run-from-source" >&2
  exit 1
fi

# Resolve the latest release tag via the redirect on /releases/latest.
# Avoids needing curl + jq + a parsed API call.
latest_url=$(curl -fsSLI -o /dev/null -w '%{url_effective}' "https://github.com/${repo}/releases/latest")
version=${latest_url##*/tag/}
if [[ -z "$version" || "$version" == "$latest_url" ]]; then
  echo "pluma installer: couldn't determine latest version from $latest_url" >&2
  exit 1
fi

archive="pluma-${version}-${os}-${arch}.tar.gz"
base="https://github.com/${repo}/releases/download/${version}"

echo "pluma: installing ${version} for ${os}-${arch}"
echo "  ↓ $base/$archive"

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

curl -fsSL "$base/$archive"        -o "$tmp/$archive"
curl -fsSL "$base/$archive.sha256" -o "$tmp/$archive.sha256"

# Verify.
( cd "$tmp" && shasum -a 256 -c "$archive.sha256" )

# Extract into the current directory.
tar -xzf "$tmp/$archive"

echo
echo "pluma: installed."
echo "  → ./pluma           starts the server on http://localhost:8787"
echo "  → ./pluma --version prints ${version}"
echo
echo "Docs: https://plumachat.app"
