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

# shellcheck source=common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/common.sh"

ensure_env_file
ensure_paths_defined

API_BASE="http://localhost:32300/api/v1/master"
NODE_ENTRYPOINT="$DEBUG_ROOT/../tests/scripts/node_entrypoint.sh"
[[ -f "$NODE_ENTRYPOINT" ]] || { echo "[ERR] node entrypoint script missing at $NODE_ENTRYPOINT" >&2; exit 1; }

TARGET_FIXED_IP="${SYS_DEBUG_NODEB_FIXED_IP:-172.30.0.200}"

ID_B_FILE="$TMP_DIR/node_id_b"
IP_INIT_FILE="$TMP_DIR/initial_ip_b"
[[ -f "$ID_B_FILE" && -f "$IP_INIT_FILE" ]] || { echo "[ERR] Required node id/ip files missing in $TMP_DIR" >&2; exit 1; }

ID_B="$(cat "$ID_B_FILE")"
IP0_B="$(cat "$IP_INIT_FILE")"

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

if [[ "$IP_BEFORE" == "$TARGET_FIXED_IP" ]]; then
  echo "[ERR] node-b current IP $IP_BEFORE already matches target $TARGET_FIXED_IP. Configure SYS_DEBUG_NODEB_FIXED_IP to a different address before rerun." >&2
  exit 1
fi

service_id() {
  compose ps -q "$1"
}

log "Recreating node-b (old IP $IP_BEFORE) with static IP $TARGET_FIXED_IP"
compose rm -sf node-b >/dev/null 2>&1 || true

CONTAINER_NAME="${SYS_DEBUG_CONTAINER_PREFIX:-argus-debug}-node-b"
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true

AGENT_BIN_PATH="$(cat "$TMP_DIR/agent_binary_path")"
[[ -f "$AGENT_BIN_PATH" ]] || { echo "[ERR] Agent binary path missing in $TMP_DIR" >&2; exit 1; }

require_docker

docker run -d \
  --name "$CONTAINER_NAME" \
  --hostname "$HOST_B" \
  --network "$SYS_DEBUG_NETWORK_NAME" \
  --ip "$TARGET_FIXED_IP" \
  --dns "${SYS_DEBUG_BIND_IP:-172.30.0.2}" \
  -e MASTER_ENDPOINT=http://master.argus.com:3000 \
  -e REPORT_INTERVAL_SECONDS=2 \
  -e ARGUS_BUILD_UID=$ARGUS_BUILD_UID \
  -e ARGUS_BUILD_GID=$ARGUS_BUILD_GID \
  -e ES_HOST=es \
  -e ES_PORT=9200 \
  -e CLUSTER=local \
  -e RACK=dev \
  -p 2021:2020 \
  -v "$SYS_DEBUG_PRIVATE_NODEB/argus/agent/$HOST_B:/private/argus/agent/$HOST_B" \
  -v "$AGENT_BIN_PATH:/usr/local/bin/argus-agent:ro" \
  -v "$NODE_ENTRYPOINT:/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

log "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" "$TARGET_FIXED_IP" <<'PY'
import json,sys
node=json.load(open(sys.argv[1]))
last0=sys.argv[2]
expected_ip=sys.argv[3]
ip=node.get("meta_data",{}).get("ip")
lu=node.get("last_updated")
if ip == expected_ip and lu and lu != last0:
    sys.exit(0)
sys.exit(1)
PY
    then
      log "node-b IP updated: $IP_BEFORE -> $TARGET_FIXED_IP"
      exit 0
    fi
  fi
done

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