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

# === MySQL 连接 ===
MYSQL_HOST="127.0.0.1"
MYSQL_PORT="3306"
MYSQL_USER="root"
MYSQL_PASS_FILE="/root/mysql_root_password.txt"
MYSQL_DB="fish"

# === SQL（取出 blacklist 表里的 ip 字段）===
SQL='SELECT DISTINCT ip FROM blacklist WHERE ip IS NOT NULL AND ip <> ""'

# === 输出路径（Nginx 读取）===
MAP_OUT="/root/ip_blacklist.map"
DENY_OUT="/root/blacklist.deny.conf"

# === Nginx 命令 ===
NGINX_TEST="nginx -t"
NGINX_RELOAD="systemctl reload nginx"

main() {
  if [[ ! -r "$MYSQL_PASS_FILE" ]]; then
    echo "❌ 找不到 MySQL 密码文件: $MYSQL_PASS_FILE" >&2
    exit 2
  fi
  MYSQL_PWD="$(<"$MYSQL_PASS_FILE")"

  tmp_map="${MAP_OUT}.tmp"
  tmp_deny="${DENY_OUT}.tmp"
  : > "$tmp_map"
  : > "$tmp_deny"

  # 从数据库抓取
  MYSQL_PWD="$MYSQL_PWD" mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" \
    -u "$MYSQL_USER" --skip-column-names --batch "$MYSQL_DB" -e "$SQL" \
    | tr -d '\r' \
    | while IFS= read -r ip; do
        ip="$(echo "$ip" | sed 's/#.*$//' | xargs || true)"
        [[ -z "$ip" ]] && continue
        printf "%s\t1;\n" "$ip" >> "$tmp_map"
        printf "deny %s;\n" "$ip" >> "$tmp_deny"
      done

  # 如果没有数据，就写一个注释，避免 Nginx include 报错
  [[ -s "$tmp_map" ]] || echo "# empty blacklist" > "$tmp_map"
  [[ -s "$tmp_deny" ]] || echo "# empty blacklist" > "$tmp_deny"

  # 原子替换
  mv "$tmp_map" "$MAP_OUT"
  mv "$tmp_deny" "$DENY_OUT"

  # 检查并重载
  $NGINX_TEST
  $NGINX_RELOAD
  echo "✅ 黑名单已更新 → $MAP_OUT / $DENY_OUT，并重载 Nginx"
}

main "$@"