#!/bin/bash

# Cloudflare 域名 DNS 管理脚本（自动安装 jq）
# 支持查看和删除记录，只需输入 API Token

# 自动安装 jq
if ! command -v jq >/dev/null 2>&1; then
    echo "🔧 未检测到 jq，正在自动安装..."
    if [ -x "$(command -v apt)" ]; then
        apt update && apt install -y jq
    elif [ -x "$(command -v yum)" ]; then
        yum install -y epel-release && yum install -y jq
    elif [ -x "$(command -v apk)" ]; then
        apk add jq
    else
        echo "❌ 无法自动安装 jq，请手动安装后再运行脚本"
        exit 1
    fi
fi

# 读取 API Token
read -p "请输入 Cloudflare API Token: " CF_API_TOKEN
CF_AUTH_HEADER="Authorization: Bearer ${CF_API_TOKEN}"
API_BASE="https://api.cloudflare.com/client/v4"

# 获取 Zone 列表
echo "🌐 正在获取你账户下的域名列表..."
zones_json=$(curl -s -X GET "$API_BASE/zones" \
    -H "Content-Type: application/json" \
    -H "$CF_AUTH_HEADER")

zones_count=$(echo "$zones_json" | jq '.result | length')
if [ "$zones_count" -eq 0 ]; then
    echo "❌ 未找到任何域名（Zone）"
    exit 1
fi

# 显示域名列表
echo "✅ 可用域名列表："
for i in $(seq 0 $((zones_count - 1))); do
    name=$(echo "$zones_json" | jq -r ".result[$i].name")
    echo "$i) $name"
done

# 选择域名
read -p "请输入你要操作的域名编号: " zone_index
ZONE_ID=$(echo "$zones_json" | jq -r ".result[$zone_index].id")
ZONE_NAME=$(echo "$zones_json" | jq -r ".result[$zone_index].name")
CF_API_DNS="$API_BASE/zones/${ZONE_ID}/dns_records"

echo "🎯 你选择的域名是：$ZONE_NAME"

# 功能：列出记录（带编号）
function list_dns_records() {
    echo "📄 正在列出 DNS 记录..."
    records_json=$(curl -s -X GET "$CF_API_DNS" \
        -H "Content-Type: application/json" \
        -H "$CF_AUTH_HEADER")

    echo "$records_json" | jq -r '
        if .success == true then
            .result[] | "\(.id) \(.type) \(.name) \(.content)"
        else
            "❌ 获取失败：" + (.errors | tostring)
        end'
}

# 功能：删除记录（选择编号）
function delete_dns_record() {
    records_json=$(curl -s -X GET "$CF_API_DNS" \
        -H "Content-Type: application/json" \
        -H "$CF_AUTH_HEADER")

    count=$(echo "$records_json" | jq '.result | length')
    if [ "$count" -eq 0 ]; then
        echo "⚠️ 没有解析记录可删除"
        return
    fi

    echo "📄 当前 DNS 记录："
    for i in $(seq 0 $((count - 1))); do
        type=$(echo "$records_json" | jq -r ".result[$i].type")
        name=$(echo "$records_json" | jq -r ".result[$i].name")
        content=$(echo "$records_json" | jq -r ".result[$i].content")
        echo "$i) [$type] $name -> $content"
    done

    read -p "请输入要删除的记录编号 [0-$(($count - 1))]: " del_index

    if ! [[ "$del_index" =~ ^[0-9]+$ ]] || [ "$del_index" -ge "$count" ]; then
        echo "❌ 编号无效"
        return
    fi

    record_id=$(echo "$records_json" | jq -r ".result[$del_index].id")
    record_name=$(echo "$records_json" | jq -r ".result[$del_index].name")
    echo "🧨 正在删除记录：$record_name ($record_id)"

    delete_resp=$(curl -s -X DELETE "$CF_API_DNS/$record_id" \
        -H "Content-Type: application/json" \
        -H "$CF_AUTH_HEADER")

    if echo "$delete_resp" | jq -e '.success' >/dev/null; then
        echo "✅ 删除成功"
    else
        echo "❌ 删除失败: $(echo "$delete_resp" | jq '.errors')"
    fi
}

# 菜单操作
function dns_menu() {
    while true; do
        echo ""
        echo "==== $ZONE_NAME DNS 管理菜单 ===="
        echo "1. 查看所有解析记录"
        echo "2. 删除某条解析记录"
        echo "0. 返回/退出"
        read -p "请选择操作 [0-2]: " choice

        case "$choice" in
            1) list_dns_records ;;
            2) delete_dns_record ;;
            0) break ;;
            *) echo "❗ 无效选择，请输入 0-2" ;;
        esac
    done
}

# 执行菜单
dns_menu
