#!/usr/bin/env bash
set -euo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")/.."

image="netsky-integration-test:stub"
name="netsky-integration-test"
root_tmp="${TMPDIR:-/tmp}/netsky-integration-test"
host_home="$root_tmp/host-home"
host_logs="$root_tmp/host-logs"
mkdir -p "$host_home" "$host_logs"

host_bin="$PWD/target/release/netsky"
host_listener_pid=""

cleanup() {
  if [[ -n "$host_listener_pid" ]]; then
    kill "$host_listener_pid" >/dev/null 2>&1 || true
    wait "$host_listener_pid" >/dev/null 2>&1 || true
  fi
  docker rm -f "$name" >/dev/null 2>&1 || true
  rm -rf "$root_tmp"
}
trap cleanup EXIT

assert_inbox_file() {
  local path="$1"
  if ! ls -1 "$path"/*.json >/dev/null 2>&1; then
    echo "expected at least one inbox file in $path" >&2
    exit 1
  fi
}

docker build -f docker/integration-test/Dockerfile -t "$image" .
cargo build --release --quiet --bin netsky

host_id="$(HOME="$host_home" "$host_bin" io iroh whoami)"
docker run -d --name "$name" "$image" sleep infinity >/dev/null
container_id="$(docker exec "$name" netsky io iroh whoami)"

HOME="$host_home" NETSKY_IROH_PEER_CONTAINER_NODEID="$container_id" \
  "$host_bin" io serve -s iroh >"$host_logs/serve.log" 2>&1 &
host_listener_pid=$!

docker exec -d "$name" sh -lc \
  "NETSKY_IROH_PEER_HOST_NODEID=$host_id netsky io serve -s iroh >/tmp/iroh-serve.log 2>&1"

sleep 2

HOME="$host_home" NETSKY_IROH_PEER_CONTAINER_NODEID="$container_id" \
  "$host_bin" io iroh send container "hello from host"

docker exec "$name" sh -lc \
  "NETSKY_IROH_PEER_HOST_NODEID=$host_id netsky io iroh send host 'hello from container'"

assert_inbox_file "$host_home/.claude/channels/iroh/container/inbox"
docker exec "$name" sh -lc 'test -d /home/netsky/.claude/channels/iroh/host/inbox && ls -1 /home/netsky/.claude/channels/iroh/host/inbox/*.json >/dev/null'

echo "scenario 1 passed: host=$host_id container=$container_id"
