#!/usr/bin/env bash
# PastCut local relay — macOS installer.
#
# What it does:
#   1. Verifies/Installs Homebrew (https://brew.sh).
#   2. Installs ffmpeg via brew if missing.
#   3. Downloads the right relay binary (arm64 / x64) from pastcut.ru.
#   4. Strips macOS quarantine, marks executable, drops it in ~/.local/bin.
#   5. Prints exact run instructions.
#
# Usage:
#   curl -fsSL https://pastcut.ru/install-relay-macos.sh | bash
#
# Source: https://github.com/izluchator/pastcut/tree/main/relay
set -euo pipefail

REPO_URL="https://github.com/izluchator/pastcut"
RELAY_BASE="https://pastcut.ru/relay"
DEST_DIR="$HOME/.local/bin"
DEST="$DEST_DIR/pastcut-relay"

bold() { printf '\033[1m%s\033[0m\n' "$*"; }
info() { printf '  %s\n' "$*"; }
ok()   { printf '\033[32m  ✓\033[0m %s\n' "$*"; }
warn() { printf '\033[33m  ⚠\033[0m %s\n' "$*"; }
fail() { printf '\033[31m  ✗\033[0m %s\n' "$*" >&2; }

if [[ "$(uname -s)" != "Darwin" ]]; then
  fail "This installer is for macOS only."
  fail "For other systems see ${REPO_URL}/tree/main/relay#readme"
  exit 1
fi

ARCH="$(uname -m)"
case "$ARCH" in
  arm64)   BIN_NAME="pastcut-relay-macos-arm64"; ARCH_LABEL="Apple Silicon" ;;
  x86_64)  BIN_NAME="pastcut-relay-macos-x64";   ARCH_LABEL="Intel" ;;
  *)       fail "Unsupported macOS arch: $ARCH"; exit 1 ;;
esac

bold "PastCut relay installer — macOS ${ARCH_LABEL}"
echo

if ! command -v brew >/dev/null 2>&1; then
  warn "Homebrew not found — installing (you may be asked for your password)…"
  NONINTERACTIVE=1 /bin/bash -c \
    "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  if [[ -x /opt/homebrew/bin/brew ]]; then
    eval "$(/opt/homebrew/bin/brew shellenv)"
  elif [[ -x /usr/local/bin/brew ]]; then
    eval "$(/usr/local/bin/brew shellenv)"
  fi
fi
ok "Homebrew: $(brew --version | head -1)"

if ! command -v ffmpeg >/dev/null 2>&1; then
  warn "ffmpeg not found — installing via brew (one-time, ~2 minutes)…"
  brew install ffmpeg >/dev/null
fi
ok "ffmpeg: $(ffmpeg -version | head -1)"

mkdir -p "$DEST_DIR"
warn "Downloading $BIN_NAME (~70 MB)…"
curl -fL --progress-bar "$RELAY_BASE/$BIN_NAME" -o "$DEST"
chmod +x "$DEST"
xattr -d com.apple.quarantine "$DEST" 2>/dev/null || true
ok "Installed to $DEST"

echo
bold "Done. To start the relay right now:"
echo
echo "    $DEST"
echo
if ! echo ":$PATH:" | grep -q ":$DEST_DIR:"; then
  warn "$DEST_DIR is not on your PATH yet."
  warn "Add this to ~/.zshrc (or ~/.bashrc) to call it as 'pastcut-relay':"
  echo
  echo "    export PATH=\"\$HOME/.local/bin:\$PATH\""
  echo
fi
echo "Keep the terminal window open while restreaming. Stop with Ctrl+C."
echo "Sources, docs, issues: $REPO_URL"
