#!/bin/sh
# Installs the payback CLI and sets it up.
#   curl -fsSL https://payback.sh | sh
# It records each Claude Code / Codex send (git tree before and after, plus the
# transcript slice) and uploads it in the background. Setup signs you in with GitHub and
# offers to upload past sessions it finds (PAYBACK_NO_AGENT=1 skips that offer, e.g. when an
# agent runs this script). Docs: https://docs.payback.sh
#
# payback is a self-contained binary: nothing else to install. It goes to
# ~/.local/share/payback (one folder per version, `current` points at the newest) with
# `payback` linked into ~/.local/bin.
set -eu

BASE="${PAYBACK_BIN_BASE:-https://payback.sh/cli/bin}"
ROOT="${PAYBACK_INSTALL_ROOT:-$HOME/.local/share/payback}"
BIN_DIR="${PAYBACK_BIN_DIR:-$HOME/.local/bin}"
# Your invite code. A personal install link (install.sh?r=...) fills this in.
REF="${PAYBACK_REF:-}"

say() { printf '%s\n' "$*"; }
fail() { printf 'error: %s\n' "$*" >&2; exit 1; }

command -v git >/dev/null 2>&1 || fail "git is required. Install it, then re-run this script."
command -v tar >/dev/null 2>&1 || fail "tar is required."

case "$(uname -s)" in Darwin) os=darwin ;; Linux) os=linux ;; *) fail "payback runs on macOS and Linux." ;; esac
case "$(uname -m)" in x86_64|amd64) arch=x86_64 ;; arm64|aarch64) arch=arm64 ;; *) arch=$(uname -m) ;; esac
PLATFORM="$os-$arch"

# A dropped connection (curl 35/56) shouldn't end the install: try each download three times.
fetch() {
  n=1
  while ! curl -fsSL "$@"; do
    [ $n -ge 3 ] && return 1
    n=$((n + 1)); sleep 2
  done
}

LINE=$(fetch "$BASE/manifest.txt" | grep "^$PLATFORM " | head -1) || true
[ -n "$LINE" ] || fail "no payback build for $PLATFORM yet. Write to founders@payback.sh and we'll add one."
# shellcheck disable=SC2086
set -- $LINE
VERSION=$2 SHA=$3 FILE=$4

TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
say "Downloading payback $VERSION for $PLATFORM ..."
fetch "$BASE/$FILE" -o "$TMP/$FILE" || fail "couldn't download $FILE (network); please run the install line again."
if command -v sha256sum >/dev/null 2>&1; then GOT=$(sha256sum "$TMP/$FILE" | cut -d' ' -f1)
else GOT=$(shasum -a 256 "$TMP/$FILE" | cut -d' ' -f1); fi
[ "$GOT" = "$SHA" ] || fail "download checksum mismatch for $FILE; please try again."

mkdir -p "$ROOT/versions" "$BIN_DIR"
if [ ! -x "$ROOT/versions/$VERSION/payback/payback" ]; then
  mkdir "$TMP/x"
  tar xzf "$TMP/$FILE" -C "$TMP/x"
  rm -rf "$ROOT/versions/$VERSION"
  mv "$TMP/x" "$ROOT/versions/$VERSION"
fi
ln -sfn "versions/$VERSION" "$ROOT/current"
ln -sf "$ROOT/current/payback/payback" "$BIN_DIR/payback"
PAYBACK="$BIN_DIR/payback"

say ""
if [ -n "$REF" ]; then
  "$PAYBACK" init --ref "$REF"
else
  "$PAYBACK" init
fi

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) case "${SHELL:-}" in *zsh) RC='~/.zshrc' ;; *bash) RC='~/.bashrc' ;; *) RC='~/.profile' ;; esac
     say "Add $BIN_DIR to your PATH to run 'payback' directly, e.g.:"
     say "  echo 'export PATH=\"$BIN_DIR:\$PATH\"' >> $RC" ;;
esac
