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

LOG_PREFIX="[AGENT-ENTRYPOINT]"
DNS_SCRIPT="/private/argus/etc/update-dns.sh"
DNS_CONF="/private/argus/etc/dns.conf"
TARGET_DOMAIN="master.argus.com"
AGENT_UID="${ARGUS_BUILD_UID:-2133}"
AGENT_GID="${ARGUS_BUILD_GID:-2015}"
AGENT_HOSTNAME="${HOSTNAME:-unknown}"
AGENT_DATA_DIR="/private/argus/agent/${AGENT_HOSTNAME}"
AGENT_HEALTH_DIR="${AGENT_DATA_DIR}/health"
RUNTIME_GROUP="argusagent"
RUNTIME_USER="argusagent"

log() {
  echo "${LOG_PREFIX} $*"
}

mkdir -p "$AGENT_DATA_DIR" "$AGENT_HEALTH_DIR"
chown -R "$AGENT_UID:$AGENT_GID" "$AGENT_DATA_DIR" "$AGENT_HEALTH_DIR" 2>/dev/null || true
chown -R "$AGENT_UID:$AGENT_GID" "/private/argus/etc" 2>/dev/null || true

if ! getent group "$AGENT_GID" >/dev/null 2>&1; then
  groupadd -g "$AGENT_GID" "$RUNTIME_GROUP"
else
  RUNTIME_GROUP="$(getent group "$AGENT_GID" | cut -d: -f1)"
fi

if ! getent passwd "$AGENT_UID" >/dev/null 2>&1; then
  useradd -u "$AGENT_UID" -g "$AGENT_GID" -M -s /bin/bash "$RUNTIME_USER"
else
  RUNTIME_USER="$(getent passwd "$AGENT_UID" | cut -d: -f1)"
fi

log "运行用户: $RUNTIME_USER ($AGENT_UID:$AGENT_GID)"

# 中文提示：等待 bind 下发的 update-dns.sh 脚本
for _ in {1..30}; do
  if [[ -x "$DNS_SCRIPT" ]]; then
    break
  fi
  log "等待 update-dns.sh 准备就绪..."
  sleep 1
done

if [[ -x "$DNS_SCRIPT" ]]; then
  log "执行 update-dns.sh 更新容器 DNS"
  while true; do
    if "$DNS_SCRIPT"; then
      log "update-dns.sh 执行成功"
      break
    fi
    log "update-dns.sh 执行失败，3 秒后重试"
    sleep 3
  done
else
  log "未获取到 update-dns.sh，使用镜像默认 DNS"
fi

# 中文提示：记录当前 dns.conf 内容，便于排查
if [[ -f "$DNS_CONF" ]]; then
  log "dns.conf 内容: $(tr '\n' ' ' < "$DNS_CONF")"
else
  log "dns.conf 暂未生成"
fi

# 中文提示：尝试解析 master 域名，失败不阻塞但会打日志
for _ in {1..30}; do
  if getent hosts "$TARGET_DOMAIN" >/dev/null 2>&1; then
    MASTER_IP=$(getent hosts "$TARGET_DOMAIN" | awk '{print $1}' | head -n 1)
    log "master.argus.com 解析成功: $MASTER_IP"
    break
  fi
  sleep 1
done

log "启动 argus-agent"
exec su -s /bin/bash -c /usr/local/bin/argus-agent "$RUNTIME_USER"
