#!/bin/sh
set -eu

BASE_URL="https://talkbank.org/downloads/chatter/releases/preview-20260226T151912Z"
TMP_DIR="${TMPDIR:-/tmp}"
TARBALL="${TMP_DIR}/chatter-macos-arm64.tar.gz"
BIN_TMP="${TMP_DIR}/chatter"
BIN_DST="/usr/local/bin/chatter"

echo "Chatter preview installer"

OS="$(uname -s)"
ARCH="$(uname -m)"

if [ "$OS" != "Darwin" ]; then
  echo "This preview installer currently supports macOS only." >&2
  exit 1
fi

if [ "$ARCH" != "arm64" ]; then
  echo "This preview installer currently supports Apple Silicon (arm64) only." >&2
  echo "Please check chatter.html for current platform availability." >&2
  exit 1
fi

echo "Downloading chatter preview..."
curl -fsSL "${BASE_URL}/chatter-macos-arm64.tar.gz" -o "$TARBALL"
tar -xzf "$TARBALL" -C "$TMP_DIR"

echo "Installing to ${BIN_DST}..."
sudo install -m 755 "$BIN_TMP" "$BIN_DST"

# Quarantine flag is present for some download paths. Ask user before removal.
if [ -r /dev/tty ]; then
  printf "Remove macOS quarantine attribute from ${BIN_DST}? [y/N] " > /dev/tty
  answer=""
  read answer < /dev/tty || true
  case "$answer" in
    y|Y|yes|YES)
      sudo xattr -d com.apple.quarantine "$BIN_DST" 2>/dev/null || true
      ;;
    *)
      echo "Skipped quarantine attribute removal."
      ;;
  esac
else
  echo "No interactive terminal detected; skipped quarantine attribute removal."
fi

echo "Install complete."
"$BIN_DST" --help
