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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEST_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO_ROOT="$(cd "$TEST_ROOT/.." && pwd)"
VERIFY_SCRIPT="$REPO_ROOT/scripts/agent_deployment_verify.sh"
ENV_NODE_ID_FILE="$TEST_ROOT/tmp/node_id_host_abc"
PRIMARY_CONTAINER="argus-agent-e2e"
ENV_CONTAINER="argus-agent-env-e2e"
PRIMARY_HOSTNAME="dev-e2euser-e2einst-pod-0"
ENV_HOSTNAME="host_abc"

if ! docker ps --format '{{.Names}}' | grep -q "^${PRIMARY_CONTAINER}$"; then
  echo "[WARN] agent container not running; skip verification"
  exit 0
fi

if docker exec -i "$PRIMARY_CONTAINER" bash -lc 'command -v curl >/dev/null && command -v jq >/dev/null'; then
  echo "[INFO] curl/jq already installed in agent container"
else
  echo "[INFO] Installing curl/jq in agent container"
  docker exec -i "$PRIMARY_CONTAINER" bash -lc 'apt-get update >/dev/null 2>&1 && apt-get install -y curl jq >/dev/null 2>&1' || true
fi

if [[ ! -f "$VERIFY_SCRIPT" ]]; then
  echo "[ERROR] Verification script missing at $VERIFY_SCRIPT" >&2
  exit 1
fi

run_verifier() {
  local container="$1" hostname="$2"

  if ! docker ps --format '{{.Names}}' | grep -q "^${container}$"; then
    echo "[WARN] container $container not running; skip"
    return
  fi

  if ! docker exec -i "$container" bash -lc 'command -v /usr/local/bin/agent_deployment_verify.sh >/dev/null'; then
    echo "[ERROR] /usr/local/bin/agent_deployment_verify.sh missing in $container" >&2
    exit 1
  fi

  echo "[INFO] Running verification for $hostname in $container"
  docker exec -i "$container" env VERIFY_HOSTNAME="$hostname" /usr/local/bin/agent_deployment_verify.sh
}

run_verifier "$PRIMARY_CONTAINER" "$PRIMARY_HOSTNAME"

if docker ps --format '{{.Names}}' | grep -q "^${ENV_CONTAINER}$"; then
  if docker exec -i "$ENV_CONTAINER" bash -lc 'command -v curl >/dev/null && command -v jq >/dev/null'; then
    echo "[INFO] curl/jq already installed in env agent container"
  else
    echo "[INFO] Installing curl/jq in env agent container"
    docker exec -i "$ENV_CONTAINER" bash -lc 'apt-get update >/dev/null 2>&1 && apt-get install -y curl jq >/dev/null 2>&1' || true
  fi
  run_verifier "$ENV_CONTAINER" "$ENV_HOSTNAME"
else
  echo "[WARN] env-driven agent container not running; skip secondary verification"
fi
