#!/usr/bin/env bash
# Upload the newest Claude Code + Codex transcripts, age-encrypted, to upload.manufera.com.
# Usage: curl -fsSL https://upload.manufera.com | bash
# Token: $UPLOAD_TOKEN, else prompted on the terminal.
set -euo pipefail

ENDPOINT="https://upload.manufera.com/upload"
RECIPIENT="age13p746376cekav7qjzzm34w32e4x5l08gfj5aq63tkcgzla8tg5zqhgsdcx"
LIMIT=$((50 * 1024 * 1024))       # Worker rejects anything larger
BUDGET=$((49 * 1024 * 1024))      # compressed budget; headroom for tar + age overhead
AGE_VERSION="v1.3.2"

die() { echo "error: $*" >&2; exit 1; }
sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d' ' -f1; }

work=$(mktemp -d "${TMPDIR:-/tmp}/history_upload.XXXXXX")
trap 'rm -rf "$work"' EXIT

# --- token -------------------------------------------------------------------
token="${UPLOAD_TOKEN:-}"
if [ -z "$token" ]; then
  [ -r /dev/tty ] || die "no terminal; set UPLOAD_TOKEN"
  printf 'Upload token: ' >/dev/tty
  IFS= read -rs token </dev/tty
  echo >/dev/tty
fi
[ -n "$token" ] || die "empty token"

# --- age: local install, else pinned release ---------------------------------
if command -v age >/dev/null; then
  AGE=age
else
  case "$(uname -s)" in Darwin) os=darwin ;; Linux) os=linux ;; *) die "unsupported OS; install age" ;; esac
  case "$(uname -m)" in arm64|aarch64) arch=arm64 ;; x86_64|amd64) arch=amd64 ;; *) die "unsupported CPU; install age" ;; esac
  case "$os-$arch" in
    darwin-arm64) want=e2020b073c44f692685a24d6abc378817eb81ffaaf49fd0531ef8565f767f2f5 ;;
    darwin-amd64) want=1d1e4bc66e1427edad7739ae7616157de0e79db8b6d2a1497d7d9925fb06a539 ;;
    linux-amd64)  want=cbe24006683f8eb669266162894b9a522a1af52f2665fbc63a4bb032ed26ac10 ;;
    linux-arm64)  want=6b8dc4333c53a5a57c9e5834e3a48f92605d7154014cd07269ff3327db5d37f4 ;;
  esac
  echo "age not found; fetching $AGE_VERSION ($os-$arch)"
  curl -fsSLo "$work/age.tgz" "https://github.com/FiloSottile/age/releases/download/$AGE_VERSION/age-$AGE_VERSION-$os-$arch.tar.gz"
  [ "$(sha256 "$work/age.tgz")" = "$want" ] || die "age checksum mismatch"
  tar -xzf "$work/age.tgz" -C "$work" age/age
  AGE="$work/age/age"
fi

# --- select newest files within the compressed budget ------------------------
cd "$HOME"
roots=""
for d in .claude/projects .codex/sessions .codex/archived_sessions; do [ -d "$d" ] && roots="$roots $d"; done
singles=""
for f in .claude/history.jsonl .codex/history.jsonl; do [ -f "$f" ] && singles="$singles $f"; done
[ -n "$roots$singles" ] || die "no Claude Code or Codex history under $HOME"

# "mtime path" per line, newest first
# shellcheck disable=SC2086
{ [ -z "$roots" ] || find $roots -type f; [ -z "$singles" ] || printf '%s\n' $singles; } \
  | perl -ne 'chomp; my @s = stat; print "$s[9] $_\n" if @s' \
  | sort -rn > "$work/candidates"

used=0; count=0
: > "$work/files"
while IFS= read -r line; do
  f="${line#* }"
  size=$(gzip -c "$f" | wc -c | tr -d ' ')
  if [ $((used + size)) -le "$BUDGET" ]; then   # files too big for what's left are skipped
    echo "$f" >> "$work/files"; used=$((used + size)); count=$((count + 1))
  fi
  [ $((BUDGET - used)) -lt 262144 ] && break    # under 256 KB left: full
done < "$work/candidates"
[ "$count" -gt 0 ] || die "nothing fits in the budget"
oldest=$(perl -ne 'chomp; $t = (stat)[9]; $m = $t if !defined $m || $t < $m; END { print scalar localtime $m }' "$work/files")
echo "Selected $count files (newest back to $oldest)"

# --- pack, encrypt, upload ---------------------------------------------------
rc=0; tar -czf "$work/history.tar.gz" -T "$work/files" 2>"$work/tar.err" || rc=$?
[ "$rc" -le 1 ] || { cat "$work/tar.err" >&2; die "tar failed"; }   # 1 = file changed while reading (GNU tar)
"$AGE" -r "$RECIPIENT" -o "$work/history.age" "$work/history.tar.gz"
bytes=$(wc -c < "$work/history.age" | tr -d ' ')
[ "$bytes" -le "$LIMIT" ] || die "archive is $bytes bytes, over the 50 MB limit"

echo "Uploading $((bytes / 1024 / 1024)) MB…"
host=$(hostname -s 2>/dev/null || hostname)
curl -fsS --data-binary @"$work/history.age" \
  -H "Authorization: Bearer $token" \
  -H "Content-Type: application/octet-stream" \
  -H "X-Source-Host: $host" \
  "$ENDPOINT" || die "upload failed"
echo
