#!/usr/bin/env bash
# =============================================================================
# fetch_deps.sh — stage the build dependencies into deps/ so a robot that has
# never seen the Unitree SDK or CycloneDDS can still build the image.
#
#   ./tools/fetch_deps.sh --from-robot unitree@10.255.254.88
#   ./tools/fetch_deps.sh --check
#
# WHY FROM A ROBOT, not from GitHub: CycloneDDS ships as compiled libraries, and
# the image is arm64. Headers are portable, `libddsc.so` is NOT — building it on
# an x86 workstation stages the wrong architecture and the in-image link fails
# in a way that looks like a code bug. A working robot already has the right
# ones, so we copy those.
#
# unitree_sdk2 is different: its repo carries prebuilt lib/aarch64/*.a, so a
# plain clone is fine — from anywhere with GitHub access.
#   git clone --depth 1 https://github.com/unitreerobotics/unitree_sdk2 deps/unitree_sdk2
#
# What lands where (build_image.sh looks in exactly these places):
#   deps/unitree_sdk2/{include,lib}
#   deps/cyclonedds/install/{include,lib}
# =============================================================================
set -uo pipefail

HERE="$(cd "$(dirname "$0")/.." && pwd)"
DEPS="$HERE/deps"
ROBOT="${ROBOT:-}"
MODE=check

while [ $# -gt 0 ]; do
  case "$1" in
    --from-robot) MODE=robot; shift; ROBOT="${1:-$ROBOT}" ;;
    --check)      MODE=check ;;
    -h|--help)    sed -n '3,22p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
    *)            echo "unknown option: $1" >&2; exit 1 ;;
  esac
  shift || true
done

g=$'\033[32m'; r=$'\033[31m'; y=$'\033[33m'; n=$'\033[0m'
ok_()  { printf '  %sOK%s    %s\n' "$g" "$n" "$1"; }
bad_() { printf '  %sMISS%s  %s\n' "$r" "$n" "$1"; }

check() {
  local rc=0
  printf '\nStaged in deps/\n'
  if [ -f "$DEPS/unitree_sdk2/lib/aarch64/libunitree_sdk2.a" ]; then
    ok_ "unitree_sdk2  ($(du -sh "$DEPS/unitree_sdk2" 2>/dev/null | cut -f1))"
  else bad_ "unitree_sdk2 — no lib/aarch64/libunitree_sdk2.a"; rc=1; fi

  if [ -f "$DEPS/cyclonedds/install/include/idl/retcode.h" ]; then
    ok_ "cyclonedds headers (incl. idl/)"
  else bad_ "cyclonedds headers — need install/include/{ddscxx,idl}"; rc=1; fi

  if ls "$DEPS"/cyclonedds/install/lib/libddsc.so* >/dev/null 2>&1; then
    local arch; arch="$(file -b "$(ls "$DEPS"/cyclonedds/install/lib/libddsc.so* | head -1)" 2>/dev/null)"
    case "$arch" in
      *aarch64*|*ARM\ aarch64*) ok_ "cyclonedds libs (aarch64)" ;;
      *) printf '  %sWRONG ARCH%s  cyclonedds libs are: %s\n' "$y" "$n" "${arch:-unknown}"
         printf '        the image is arm64 — restage from a robot\n'; rc=1 ;;
    esac
  else bad_ "cyclonedds libs — need install/lib/libddsc.so*"; rc=1; fi
  return $rc
}

if [ "$MODE" = check ]; then
  check; rc=$?
  [ $rc -eq 0 ] && printf '\n%sdeps/ is complete%s — this project can build the image on a robot with no system SDK.\n' "$g" "$n" \
                || printf '\nStage the rest with:  %s --from-robot unitree@<ip>\n' "$0"
  exit $rc
fi

[ -n "$ROBOT" ] || { echo "give a robot: --from-robot unitree@<ip>" >&2; exit 1; }
command -v rsync >/dev/null || { echo "rsync not installed" >&2; exit 1; }

echo ">> staging CycloneDDS from $ROBOT (headers + aarch64 libs)"
mkdir -p "$DEPS/cyclonedds/install"
# Prefer the source checkout's install prefix: it is the one that carries the idl/
# headers a plain `make install` of the C++ side leaves out.
rsync -az --info=stats0 -e "ssh -o ConnectTimeout=8" \
      "$ROBOT:~/cyclonedds/install/include" "$ROBOT:~/cyclonedds/install/lib" \
      "$DEPS/cyclonedds/install/" 2>/dev/null \
  || echo "   (no ~/cyclonedds/install on that robot — trying /usr/local)"

# Fill any gap from /usr/local, which is where the runtime libs actually live.
[ -f "$DEPS/cyclonedds/install/include/idl/retcode.h" ] || \
  rsync -az -e "ssh -o ConnectTimeout=8" "$ROBOT:/usr/local/include/" \
        "$DEPS/cyclonedds/install/include/" 2>/dev/null
ls "$DEPS"/cyclonedds/install/lib/libddsc.so* >/dev/null 2>&1 || {
  mkdir -p "$DEPS/cyclonedds/install/lib"
  rsync -azL -e "ssh -o ConnectTimeout=8" \
        "$ROBOT:/usr/local/lib/libddsc*" "$ROBOT:/usr/local/lib/libddscxx*" \
        "$ROBOT:/usr/local/lib/libcyclonedds*" "$ROBOT:/usr/local/lib/libdds_security_*" \
        "$DEPS/cyclonedds/install/lib/" 2>/dev/null; }

if [ ! -f "$DEPS/unitree_sdk2/lib/aarch64/libunitree_sdk2.a" ]; then
  echo ">> staging unitree_sdk2 from $ROBOT"
  mkdir -p "$DEPS/unitree_sdk2"
  rsync -az --exclude '.git/' -e "ssh -o ConnectTimeout=8" \
        "$ROBOT:~/unitree_sdk2/include" "$ROBOT:~/unitree_sdk2/lib" "$DEPS/unitree_sdk2/" 2>/dev/null
fi

check
