#!/usr/bin/env bash
# =============================================================================
# bundle.sh — pack the manual recorder into one file you can copy anywhere.
#
#   ./bundle.sh                  -> manual_recorder_<date>.tar.gz  (~2 MB)
#   ./bundle.sh --with-takes     -> also include DataG1/*.jsonl
#   ./bundle.sh --out /tmp/x.tar.gz
#
# What goes in: the recorder itself, its launcher, the home pose, the vendored
# Unitree python SDK, and a README. That is everything the CLI path needs except
# the compiled DDS bindings, which cannot travel in a tarball — the README says
# how to get them.
#
# This is the fallback for when Docker, the dashboard, or the network are not
# available: unpack on any machine that can reach the robot's DDS interface and
# record from a terminal.
# =============================================================================
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
REPO="$(cd "$HERE/.." && pwd)"
WITH_TAKES=0
OUT="$PWD/manual_recorder_$(date +%Y%m%d).tar.gz"

while [ $# -gt 0 ]; do
  case "$1" in
    --with-takes) WITH_TAKES=1 ;;
    --out) shift; OUT="$1" ;;
    -h|--help) sed -n '3,15p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *) echo "unknown option: $1" >&2; exit 1 ;;
  esac
  shift
done

STAGE="$(mktemp -d)"
trap 'rm -rf "$STAGE"' EXIT
K="$STAGE/manual_recorder"
mkdir -p "$K/recorder" "$K/vendor"

cp "$HERE/g1_record_replay.py" "$HERE/record.sh" "$K/recorder/"
[ -f "$HERE/README.md" ]      && cp "$HERE/README.md"      "$K/recorder/"
[ -f "$HERE/arm_home.jsonl" ] && cp "$HERE/arm_home.jsonl" "$K/recorder/"
chmod +x "$K/recorder/record.sh"

# The SDK is pure python and travels fine; the compiled cyclonedds bindings do
# not, which is why the README leads with the two runtimes that already have them.
if [ -d "$REPO/vendor/unitree_sdk2_python" ]; then
  cp -r "$REPO/vendor/unitree_sdk2_python" "$K/vendor/"
  rm -rf "$K/vendor/unitree_sdk2_python/.git" 2>/dev/null || true
else
  echo ">> note: no vendored SDK at $REPO/vendor — bundling without it"
fi

if [ "$WITH_TAKES" = 1 ] && [ -d "$HERE/DataG1" ]; then
  mkdir -p "$K/recorder/DataG1"
  cp "$HERE"/DataG1/*.jsonl "$K/recorder/DataG1/" 2>/dev/null || true
  echo ">> takes included: $(ls "$K/recorder/DataG1" | wc -l) file(s)"
fi

tar -czf "$OUT" -C "$STAGE" manual_recorder
echo ">> wrote $OUT  ($(du -h "$OUT" | cut -f1))"
echo "   unpack:  tar -xzf $(basename "$OUT")  &&  cd manual_recorder/recorder"
echo "   check:   ./record.sh doctor"
