#!/bin/sh
#
# pre-push hook: on Linux, when pushing to main, rebuild adamo-network
# and upload the binary to S3 for the current architecture.
#
# Install: git config core.hooksPath ./hooks
#
set -eu

# ── Only run on Linux ────────────────────────────────────────────────────

if [ "$(uname -s)" != "Linux" ]; then
  exit 0
fi

# ── Check if pushing to main ─────────────────────────────────────────────

PUSHING_MAIN=false
while read -r local_ref local_sha remote_ref remote_sha; do
  case "$remote_ref" in
    refs/heads/main) PUSHING_MAIN=true ;;
  esac
done

if [ "$PUSHING_MAIN" = false ]; then
  exit 0
fi

# ── Detect architecture and build features ───────────────────────────────

ARCH=$(uname -m)
CARGO_FEATURES=""
IS_JETSON=false

if [ -f /proc/device-tree/model ] && grep -qi "tegra\|jetson" /proc/device-tree/model 2>/dev/null; then
  IS_JETSON=true
fi

case "$ARCH" in
  aarch64|arm64)
    BINARY_SUFFIX="aarch64-linux"
    if [ "$IS_JETSON" = true ]; then
      CARGO_FEATURES="--features jetson"
    fi
    ;;
  x86_64)
    BINARY_SUFFIX="x86_64-linux"
    ;;
  *)
    echo "[pre-push] Unsupported architecture: $ARCH, skipping build"
    exit 0
    ;;
esac

# ── Build and upload ─────────────────────────────────────────────────────

echo "[pre-push] Building adamo-network for $ARCH..."

cargo build --release $CARGO_FEATURES 2>&1 | tail -5

BINARY="target/release/adamo-network"
if [ ! -f "$BINARY" ]; then
  echo "[pre-push] ERROR: build failed, binary not found"
  exit 1
fi

echo "[pre-push] Uploading binary as adamo-network-${BINARY_SUFFIX}..."
aws s3 cp "$BINARY" "s3://adamo-downloads/bin/adamo-network-${BINARY_SUFFIX}" \
  --content-type application/octet-stream

echo "[pre-push] Uploading install script..."
aws s3 cp scripts/install.sh s3://adamo-downloads/install.sh \
  --content-type text/plain

echo "[pre-push] Done. adamo-network-${BINARY_SUFFIX} updated at install.adamohq.com"
