#!/bin/sh
# npubmail installer: downloads the npubmail CLI and MCP server for this
# machine from https://npubmail.com, verifies SHA-256 checksums, installs to ~/.local/bin.
# No root, no compiler, no repository access needed.
set -eu
BASE="https://npubmail.com"
DIR="${NPUBMAIL_BIN:-$HOME/.local/bin}"

os=$(uname -s | tr '[:upper:]' '[:lower:]')
case "$os" in linux|darwin) ;; *) echo "unsupported OS: $os (Windows: download $BASE/dl/npubmail-windows-amd64.exe)"; exit 1;; esac
arch=$(uname -m)
case "$arch" in x86_64|amd64) arch=amd64;; aarch64|arm64) arch=arm64;; *) echo "unsupported CPU: $arch"; exit 1;; esac

if command -v curl >/dev/null 2>&1; then get() { curl -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then get() { wget -q "$1" -O "$2"; }
else echo "need curl or wget"; exit 1; fi
if command -v sha256sum >/dev/null 2>&1; then sum() { sha256sum "$1" | cut -d' ' -f1; }
else sum() { shasum -a 256 "$1" | cut -d' ' -f1; }; fi

tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
get "$BASE/dl/SHA256SUMS" "$tmp/SHA256SUMS"
mkdir -p "$DIR"
for b in npubmail npubmail-mcp; do
  f="$b-$os-$arch"
  get "$BASE/dl/$f" "$tmp/$f"
  want=$(grep " $f\$" "$tmp/SHA256SUMS" | cut -d' ' -f1)
  [ -n "$want" ] && [ "$(sum "$tmp/$f")" = "$want" ] || { echo "checksum mismatch for $f"; exit 1; }
  install -m 755 "$tmp/$f" "$DIR/$b" 2>/dev/null || { cp "$tmp/$f" "$DIR/$b"; chmod 755 "$DIR/$b"; }
done

echo "installed: $DIR/npubmail, $DIR/npubmail-mcp"
case ":$PATH:" in *":$DIR:"*) ;; *) echo "note: add $DIR to PATH (export PATH=\"$DIR:\$PATH\")";; esac
echo
echo "next:  npubmail init myagent     # creates key + myagent@npubmail.com"
echo "guide: $BASE/llms.txt"
