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

# 中文提示：确保共享目录与 DNS 相关脚本存在
DNS_DIR="/private/argus/etc"
DNS_SCRIPT="${DNS_DIR}/update-dns.sh"
MASTER_DOMAIN_FILE="${DNS_DIR}/master.argus.com"

mkdir -p "$DNS_DIR"

if [[ -x "$DNS_SCRIPT" ]]; then
  echo "[INFO] Running update-dns.sh before master starts"
  # 中文提示：若脚本存在则执行，保证容器使用 bind 作为 DNS
  "$DNS_SCRIPT" || echo "[WARN] update-dns.sh execution failed"
else
  echo "[WARN] DNS update script not found or not executable: $DNS_SCRIPT"
fi

# 中文提示：记录 master 当前 IP，供 bind 服务同步
MASTER_IP=$(ifconfig | grep -A 1 eth0 | grep inet | awk '{print $2}' || true)
if [[ -n "${MASTER_IP}" ]]; then
  echo "current IP: ${MASTER_IP}"
  echo "${MASTER_IP}" > "$MASTER_DOMAIN_FILE"
else
  echo "[WARN] Failed to detect master IP via ifconfig"
fi

WORKERS=${GUNICORN_WORKERS:-4}
BIND_ADDR=${GUNICORN_BIND:-0.0.0.0:3000}
EXTRA_OPTS=${GUNICORN_EXTRA_ARGS:-}

if [[ -n "$EXTRA_OPTS" ]]; then
  read -r -a EXTRA_ARRAY <<< "$EXTRA_OPTS"
else
  EXTRA_ARRAY=()
fi

exec gunicorn --bind "$BIND_ADDR" --workers "$WORKERS" "${EXTRA_ARRAY[@]}" "app:create_app()"
