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

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

PRIVATE_ROOT=""
PRIVATE_CORE="$SYS_DEBUG_PRIVATE_CORE"
PRIVATE_NODEA="$SYS_DEBUG_PRIVATE_NODEA"
PRIVATE_NODEB="$SYS_DEBUG_PRIVATE_NODEB"
TMP_DIR_VAL="$SYS_DEBUG_TMP_DIR"
NETWORK_NAME="$SYS_DEBUG_NETWORK_NAME"
NETWORK_SUBNET="$SYS_DEBUG_NETWORK_SUBNET"
NETWORK_GATEWAY="$SYS_DEBUG_NETWORK_GATEWAY"
PROJECT_NAME="$SYS_DEBUG_PROJECT_NAME"
CONTAINER_PREFIX="$SYS_DEBUG_CONTAINER_PREFIX"
NODEB_FIXED_IP=${SYS_DEBUG_NODEB_FIXED_IP:-172.30.0.200}

usage() {
  cat <<EOF
Usage: ${0##*/} [--private-root PATH] [--private-core PATH] \
                 [--private-nodea PATH] [--private-nodeb PATH] \
                 [--tmp-dir PATH] [--network-name NAME] \
                 [--network-subnet CIDR] [--network-gateway IP]

Prepare directories, build agent binary, and write .env for debug stack.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --private-root)
      shift; [[ $# -gt 0 ]] || { echo "--private-root requires value" >&2; exit 1; }
      PRIVATE_ROOT="$1"
      ;;
    --private-root=*)
      PRIVATE_ROOT="${1#*=}"
      ;;
    --private-core)
      shift; [[ $# -gt 0 ]] || { echo "--private-core requires value" >&2; exit 1; }
      PRIVATE_CORE="$1"
      ;;
    --private-core=*)
      PRIVATE_CORE="${1#*=}"
      ;;
    --private-nodea)
      shift; [[ $# -gt 0 ]] || { echo "--private-nodea requires value" >&2; exit 1; }
      PRIVATE_NODEA="$1"
      ;;
    --private-nodea=*)
      PRIVATE_NODEA="${1#*=}"
      ;;
    --private-nodeb)
      shift; [[ $# -gt 0 ]] || { echo "--private-nodeb requires value" >&2; exit 1; }
      PRIVATE_NODEB="$1"
      ;;
    --private-nodeb=*)
      PRIVATE_NODEB="${1#*=}"
      ;;
    --tmp-dir)
      shift; [[ $# -gt 0 ]] || { echo "--tmp-dir requires value" >&2; exit 1; }
      TMP_DIR_VAL="$1"
      ;;
    --tmp-dir=*)
      TMP_DIR_VAL="${1#*=}"
      ;;
    --network-name)
      shift; [[ $# -gt 0 ]] || { echo "--network-name requires value" >&2; exit 1; }
      NETWORK_NAME="$1"
      ;;
    --network-name=*)
      NETWORK_NAME="${1#*=}"
      ;;
    --network-subnet)
      shift; [[ $# -gt 0 ]] || { echo "--network-subnet requires value" >&2; exit 1; }
      NETWORK_SUBNET="$1"
      ;;
    --network-subnet=*)
      NETWORK_SUBNET="${1#*=}"
      ;;
    --network-gateway)
      shift; [[ $# -gt 0 ]] || { echo "--network-gateway requires value" >&2; exit 1; }
      NETWORK_GATEWAY="$1"
      ;;
    --network-gateway=*)
      NETWORK_GATEWAY="${1#*=}"
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
  shift
done

if [[ -n "$PRIVATE_ROOT" ]]; then
  PRIVATE_CORE="$PRIVATE_ROOT/private"
  PRIVATE_NODEA="$PRIVATE_ROOT/private-nodea"
  PRIVATE_NODEB="$PRIVATE_ROOT/private-nodeb"
fi

PRIVATE_CORE=$(abs_path "$PRIVATE_CORE")
PRIVATE_NODEA=$(abs_path "$PRIVATE_NODEA")
PRIVATE_NODEB=$(abs_path "$PRIVATE_NODEB")
TMP_DIR_VAL=$(abs_path "$TMP_DIR_VAL")

log "Preparing directories under $PRIVATE_CORE"
mkdir -p \
  "$PRIVATE_CORE/argus/etc" \
  "$PRIVATE_CORE/argus/bind" \
  "$PRIVATE_CORE/argus/master" \
  "$PRIVATE_CORE/argus/metric/prometheus" \
  "$PRIVATE_CORE/argus/log/elasticsearch" \
  "$PRIVATE_CORE/argus/log/kibana" \
  "$PRIVATE_NODEA/argus/agent/$HOST_A/health" \
  "$PRIVATE_NODEB/argus/agent/$HOST_B/health" \
  "$TMP_DIR_VAL"

log "Aligning ownership for core directories"
chown -R "${ARGUS_BUILD_UID}:${ARGUS_BUILD_GID}" \
  "$PRIVATE_CORE/argus/log/elasticsearch" \
  "$PRIVATE_CORE/argus/log/kibana" \
  "$PRIVATE_CORE/argus/etc" 2>/dev/null || true

log "Distributing update-dns.sh"
BIND_UPDATE_SRC="$REPO_ROOT/src/bind/build/update-dns.sh"
BIND_UPDATE_DEST="$PRIVATE_CORE/argus/etc/update-dns.sh"
if [[ -f "$BIND_UPDATE_SRC" ]]; then
  cp "$BIND_UPDATE_SRC" "$BIND_UPDATE_DEST"
  chmod +x "$BIND_UPDATE_DEST"
else
  echo "[WARN] Missing $BIND_UPDATE_SRC" >&2
fi

require_docker

ensure_image() {
  local image="$1"
  if ! docker image inspect "$image" >/dev/null 2>&1; then
    echo "[ERR] Missing image: $image. Run ./build/build_images.sh" >&2
    exit 1
  fi
}

log "Ensuring required images exist"
ensure_image "${ES_IMAGE_TAG:-argus-elasticsearch:latest}"
ensure_image "${KIBANA_IMAGE_TAG:-argus-kibana:latest}"
ensure_image "${BIND_IMAGE_TAG:-argus-bind9:latest}"
ensure_image "${MASTER_IMAGE_TAG:-argus-master:latest}"

log "Building agent binary"
pushd "$REPO_ROOT/src/agent" >/dev/null
./scripts/build_binary.sh
popd >/dev/null

AGENT_BIN="$REPO_ROOT/src/agent/dist/argus-agent"
if [[ ! -x "$AGENT_BIN" ]]; then
  echo "[ERR] Agent binary not found at $AGENT_BIN" >&2
  exit 1
fi
echo "$AGENT_BIN" > "$TMP_DIR_VAL/agent_binary_path"

log "Preparing environment file contents"
tmp_env="$(mktemp)"
cat > "$tmp_env" <<EOF
SYS_DEBUG_PRIVATE_CORE=$PRIVATE_CORE
SYS_DEBUG_PRIVATE_NODEA=$PRIVATE_NODEA
SYS_DEBUG_PRIVATE_NODEB=$PRIVATE_NODEB
SYS_DEBUG_TMP_DIR=$TMP_DIR_VAL
SYS_DEBUG_NETWORK_NAME=$NETWORK_NAME
SYS_DEBUG_NETWORK_SUBNET=$NETWORK_SUBNET
SYS_DEBUG_NETWORK_GATEWAY=$NETWORK_GATEWAY
SYS_DEBUG_PROJECT_NAME=$PROJECT_NAME
SYS_DEBUG_CONTAINER_PREFIX=$CONTAINER_PREFIX
SYS_DEBUG_NODEA_HOST=$HOST_A
SYS_DEBUG_NODEB_HOST=$HOST_B
SYS_DEBUG_BIND_IP=${SYS_DEBUG_BIND_IP:-172.30.0.2}
SYS_DEBUG_MASTER_IP=${SYS_DEBUG_MASTER_IP:-172.30.0.10}
SYS_DEBUG_ES_IP=${SYS_DEBUG_ES_IP:-172.30.0.20}
SYS_DEBUG_KIBANA_IP=${SYS_DEBUG_KIBANA_IP:-172.30.0.30}
SYS_DEBUG_NODEA_IP=${SYS_DEBUG_NODEA_IP:-172.30.0.101}
SYS_DEBUG_NODEB_IP=${SYS_DEBUG_NODEB_IP:-172.30.0.102}
SYS_DEBUG_NODEB_FIXED_IP=$NODEB_FIXED_IP
ARGUS_BUILD_UID=$ARGUS_BUILD_UID
ARGUS_BUILD_GID=$ARGUS_BUILD_GID
EOF

if [[ -f "$ENV_FILE" ]]; then
  if cmp -s "$tmp_env" "$ENV_FILE"; then
    log ".env already up-to-date"
    rm -f "$tmp_env"
    if [[ ! -f "$DEBUG_ROOT/.env.lock" ]]; then
      cp "$ENV_FILE" "$DEBUG_ROOT/.env.lock"
    fi
  else
    mv "$ENV_FILE" "$ENV_FILE.bak"
    mv "$tmp_env" "$ENV_FILE"
    cp "$ENV_FILE" "$DEBUG_ROOT/.env.lock"
    log "Bootstrap updated .env (previous saved at ${ENV_FILE}.bak)"
  fi
else
  mv "$tmp_env" "$ENV_FILE"
  cp "$ENV_FILE" "$DEBUG_ROOT/.env.lock"
  log "Bootstrap created .env at $ENV_FILE"
fi
