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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CONFIG_FILE="${IOP_NODE_CONFIG:-$REPO_ROOT/configs/node.yaml}"
CONFIG_DIR="$(cd "$(dirname "$CONFIG_FILE")" && pwd)"

cd "$REPO_ROOT"
echo "[node] config=$CONFIG_FILE"

EDGE_ADDR="${IOP_EDGE_ADDR:-$(sed -nE 's/^[[:space:]]*edge_addr:[[:space:]]*"?([^"#]+)"?[[:space:]]*(#.*)?$/\1/p' "$CONFIG_FILE" | head -n1)}"
EDGE_ADDR="${EDGE_ADDR//[[:space:]]/}"
EDGE_HOST="${EDGE_ADDR%:*}"
EDGE_PORT="${EDGE_ADDR##*:}"
EDGE_HOST="${EDGE_HOST#[}"
EDGE_HOST="${EDGE_HOST%]}"
WAIT_TIMEOUT="${IOP_NODE_WAIT_TIMEOUT:-30}"
WAIT_INTERVAL="${IOP_NODE_WAIT_INTERVAL:-1}"

if [[ -z "$EDGE_HOST" || -z "$EDGE_PORT" || "$EDGE_HOST" == "$EDGE_PORT" ]]; then
  echo "[node] invalid edge_addr in $CONFIG_FILE: ${EDGE_ADDR:-<empty>}" >&2
  exit 1
fi

echo "[node] waiting for edge at $EDGE_HOST:$EDGE_PORT timeout=${WAIT_TIMEOUT}s"
deadline=$((SECONDS + WAIT_TIMEOUT))
while ! timeout 1 bash -c 'cat < /dev/null > /dev/tcp/"$1"/"$2"' _ "$EDGE_HOST" "$EDGE_PORT" 2>/dev/null; do
  if (( SECONDS >= deadline )); then
    echo "[node] edge is not reachable at $EDGE_HOST:$EDGE_PORT; start ./scripts/dev/edge.sh first or update configs/node.yaml transport.edge_addr" >&2
    exit 1
  fi
  sleep "$WAIT_INTERVAL"
done
echo "[node] edge is reachable"

NODE_BIN="${IOP_NODE_BIN:-$REPO_ROOT/build/dev/iop-node}"
if [[ -z "${IOP_NODE_BIN:-}" ]]; then
  mkdir -p "$(dirname "$NODE_BIN")"
  (cd "$REPO_ROOT" && go build -o "$NODE_BIN" ./apps/node/cmd/node)
fi

cd "$CONFIG_DIR"
exec "$NODE_BIN" serve --config "$CONFIG_FILE"
