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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TMP_DIR="$TEST_ROOT/tmp"
REPO_ROOT="$(cd "$TEST_ROOT/../../.." && pwd)"

API_BASE="http://localhost:32300/api/v1/master"

ID_B="$(cat "$TMP_DIR/node_id_b")"
IP0_B="$(cat "$TMP_DIR/initial_ip_b")"

detail_before="$TMP_DIR/node_b_before.json"
curl -fsS "$API_BASE/nodes/$ID_B" -o "$detail_before"
LAST0=$(python3 - "$detail_before" <<'PY'
import json,sys
node=json.load(open(sys.argv[1]))
print(node.get("last_updated",""))
PY
)
IP_BEFORE=$(python3 - "$detail_before" <<'PY'
import json,sys
node=json.load(open(sys.argv[1]))
print(node.get("meta_data",{}).get("ip",""))
PY
)

if [[ "$IP_BEFORE" != "$IP0_B" ]]; then
  echo "[ERR] Expected initial IP $IP0_B for node-b, got $IP_BEFORE" >&2
  exit 1
fi

compose() {
  if docker compose version >/dev/null 2>&1; then
    docker compose "$@"
  else
    docker-compose "$@"
  fi
}

echo "[INFO] Recreating node-b with static IP 172.29.0.200..."
pushd "$TEST_ROOT" >/dev/null
compose -p argus-sys rm -sf node-b || true
popd >/dev/null

docker rm -f argus-node-b >/dev/null 2>&1 || true

AGENT_BIN_PATH="$(cat "$TMP_DIR/agent_binary_path")"

docker run -d \
  --name argus-node-b \
  --hostname dev-yyrshare-uuuu10-ep2f-pod-0 \
  --network argus-sys-net \
  --ip 172.29.0.200 \
  --dns 172.29.0.2 \
  -e MASTER_ENDPOINT=http://master.argus.com:3000 \
  -e REPORT_INTERVAL_SECONDS=2 \
  -e ARGUS_BUILD_UID=${ARGUS_BUILD_UID:-2133} \
  -e ARGUS_BUILD_GID=${ARGUS_BUILD_GID:-2015} \
  -e ES_HOST=es \
  -e ES_PORT=9200 \
  -p 2021:2020 \
  -v "$TEST_ROOT/private-nodeb/argus/agent/dev-yyrshare-uuuu10-ep2f-pod-0:/private/argus/agent/dev-yyrshare-uuuu10-ep2f-pod-0" \
  -v "$AGENT_BIN_PATH:/usr/local/bin/argus-agent:ro" \
  -v "$SCRIPT_DIR/node_entrypoint.sh:/usr/local/bin/node-entrypoint.sh:ro" \
  -v "$REPO_ROOT/src/log/fluent-bit/build/start-fluent-bit.sh:/assets/start-fluent-bit.sh:ro" \
  -v "$REPO_ROOT/src/log/fluent-bit/build/etc:/assets/fluent-bit/etc:ro" \
  -v "$REPO_ROOT/src/log/fluent-bit/build/packages:/assets/fluent-bit/packages:ro" \
  --entrypoint /usr/local/bin/node-entrypoint.sh \
  ubuntu:22.04 >/dev/null

echo "[INFO] Waiting for node-b to re-register with new IP..."
for _ in {1..40}; do
  sleep 3
  if curl -fsS "$API_BASE/nodes/$ID_B" -o "$TMP_DIR/node_b_after.json"; then
    if python3 - "$TMP_DIR/node_b_after.json" "$LAST0" <<'PY'
import json,sys
node=json.load(open(sys.argv[1]))
last0=sys.argv[2]
ip=node.get("meta_data",{}).get("ip")
lu=node.get("last_updated")
assert ip=="172.29.0.200"
assert lu and lu!=last0
PY
    then
      echo "[OK] node-b re-registered with new IP 172.29.0.200"
      exit 0
    fi
  fi
done

echo "[ERR] node-b did not update to IP 172.29.0.200 in time" >&2
exit 1
