#!/bin/sh
# treacle installer — https://treacle.dev
set -eu

case "$(uname -sm)" in
  "Darwin arm64") target=darwin-arm64 ;;
  "Linux x86_64" | "Linux amd64") target=linux-x64 ;;
  "Linux aarch64" | "Linux arm64") target=linux-arm64 ;;
  "Darwin x86_64") echo "treacle runs on Apple silicon Macs, not Intel ones." >&2; exit 1 ;;
  "Linux armv"*) echo "treacle needs a 64-bit OS; this one is 32-bit ($(uname -m)). On a Raspberry Pi, install the 64-bit Raspberry Pi OS." >&2; exit 1 ;;
  *) echo "treacle runs on macOS (Apple silicon) and Linux (x64, arm64), not $(uname -sm). On Windows, run this inside WSL 2." >&2; exit 1 ;;
esac
os=${target%%-*}
pub='-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAx38F7JLQeyqtMHwNEv1m1eiRU+FualW4kkqht4zmq6Y=
-----END PUBLIC KEY-----'

if [ "$os" = "linux" ]; then
  if [ -z "$pub" ]; then
    echo "Linux builds are not published yet — nothing was installed." >&2
    exit 1
  fi
  if ! command -v openssl >/dev/null 2>&1; then
    echo "checking the download's signature needs openssl:  sudo apt install openssl  (or your distro's package), then run this again." >&2
    exit 1
  fi
fi

dir="$HOME/.treacle/bin"
mkdir -p "$dir"
tmp="$dir/treacle.tmp"
trap 'rm -f "$tmp" "$tmp.json" "$tmp.msg" "$tmp.sig" "$tmp.pub"' EXIT
echo "pouring treacle ..."
if ! curl -fsSL "https://treacle.dev/dl/treacle-$target.json" -o "$tmp.json"; then
  echo "could not read the release manifest — nothing was installed." >&2
  exit 1
fi
field() { sed -nE 's/.*"'"$1"'": *"([^"]+)".*/\1/p' "$tmp.json"; }
want=$(field sha256)
case "$want" in
  *[!0-9a-f]* | "") echo "could not read the release manifest — nothing was installed." >&2; exit 1 ;;
esac
curl -fsSL "https://treacle.dev/dl/treacle-$target?build=$(field build)&sha256=$want" -o "$tmp"
if command -v sha256sum >/dev/null 2>&1; then got=$(sha256sum "$tmp" | cut -d' ' -f1); else got=$(shasum -a 256 "$tmp" | cut -d' ' -f1); fi
if [ "$got" != "$want" ]; then
  echo "the download does not match the release manifest (sha256) — nothing was installed." >&2
  exit 1
fi
if [ "$os" = "darwin" ]; then
  # Signed by Continuata's Developer ID as app.treacle: the same requirement
  # macOS privacy grants are pinned to, so a binary that passes keeps them.
  if ! codesign --verify --strict -R='anchor apple generic and identifier "app.treacle" and certificate leaf[subject.OU] = "GXD2K5H977"' "$tmp" 2>/dev/null; then
    echo "the download is not signed by treacle's Developer ID — nothing was installed." >&2
    exit 1
  fi
  echo "verified: sha256 matches the release, signed by Continuata Ltd (GXD2K5H977)"
else
  # Linux has no platform signature: the manifest is signed with treacle's
  # release key (Ed25519) over the file, the build and this sha256.
  printf '%s
' "$pub" > "$tmp.pub"
  printf '%s' "treacle treacle-$target $(field build) $got" > "$tmp.msg"
  field sig | base64 -d > "$tmp.sig" 2>/dev/null || true
  if ! openssl pkeyutl -verify -pubin -inkey "$tmp.pub" -rawin -in "$tmp.msg" -sigfile "$tmp.sig" >/dev/null 2>&1; then
    echo "the download is not signed by treacle's release key — nothing was installed." >&2
    exit 1
  fi
  echo "verified: sha256 matches the release, signed by treacle's release key"
fi
chmod +x "$tmp"
mv "$tmp" "$dir/treacle"

if [ -w /usr/local/bin ] 2>/dev/null; then
  ln -sf "$dir/treacle" /usr/local/bin/treacle
  echo "installed: /usr/local/bin/treacle"
  on_path=1
else
  echo "installed: $dir/treacle"
  on_path=0
fi

# Put it on PATH for future shells rather than leaving the user to find an
# editor. The block is marked and only written once, so re-running is safe.
if [ "$on_path" = "0" ]; then
  bashrc="$HOME/.bash_profile"
  [ "$os" = "linux" ] && bashrc="$HOME/.bashrc"
  case "$(basename "${SHELL:-/bin/sh}")" in
    zsh)  rc="$HOME/.zshrc";                 line='export PATH="$HOME/.treacle/bin:$PATH"' ;;
    bash) rc="$bashrc";                      line='export PATH="$HOME/.treacle/bin:$PATH"' ;;
    fish) rc="$HOME/.config/fish/config.fish"; line='set -gx PATH $HOME/.treacle/bin $PATH' ;;
    *)    rc=""; line='export PATH="$HOME/.treacle/bin:$PATH"' ;;
  esac
  if [ -n "$rc" ]; then
    mkdir -p "$(dirname "$rc")"
    if [ -f "$rc" ] && grep -q "# >>> treacle path >>>" "$rc" 2>/dev/null; then
      echo "PATH already set up in $rc"
    else
      {
        echo ""
        echo "# >>> treacle path >>>"
        echo "$line"
        echo "# <<< treacle path <<<"
      } >> "$rc"
      echo "added to PATH in $rc"
    fi
  else
    echo "add it to your PATH:  $line"
  fi
fi

if ! command -v tmux >/dev/null 2>&1; then
  echo
  if [ "$os" = "linux" ]; then
    echo "treacle runs its sessions in tmux, which is not installed:  sudo apt install tmux  (or your distro's package)"
  else
    echo "treacle runs its sessions in tmux, which is not installed:  brew install tmux"
  fi
fi

echo
echo "next, on the machine that stays on:"
if [ "$on_path" = "1" ]; then
  echo "  treacle setup"
else
  # This script is a child process and cannot change the PATH of the shell you
  # are standing in — nothing piped to sh can. So give a command that needs no
  # PATH at all, and it is already correct.
  echo "  ~/.treacle/bin/treacle setup"
  echo
  echo "(new terminals will find treacle on their own; for this one, either use"
  echo " the full path above or run:  exec $SHELL -l)"
fi
echo
echo "setup ends with a QR for your phone. It reaches this machine through your own"
echo "Cloudflare domain (free account; the address never changes), a temporary address,"
echo "or Tailscale if you already use it. Only a pairing door is public; the app is not."
