#!/bin/bash
export LANG=zh_CN.UTF-8
auth_email="***.***"    #你的CloudFlare注册账户邮箱
auth_key="XXXXXXXXXXX"   #你的CloudFlare账户全球key
zone_name="XXX.XXX"     #你的主域名
record_name="cl"    #自动更新的二级域名前缀
record_count=5 

echo
echo "正在获取本机公网IP..."
# 依次尝试多个测速/IP获取接口，哪个通了用哪个
my_ip=$(curl -s --connect-timeout 5 4.ipw.cn)
[ -z "$my_ip" ] && my_ip=$(curl -s --connect-timeout 5 ifconfig.me)
[ -z "$my_ip" ] && my_ip=$(curl -s --connect-timeout 5 ip.sb)

if [ -z "$my_ip" ]; then
    echo "【警告】无法通过外部接口获取公网IP（可能接口被去广告拦截），但网络似乎是通的，继续尝试连接 Cloudflare..."
else
    echo "你的IP地址是: $my_ip ,请确认为本机未经过代理的地址"
fi

echo '小道笔记：https://www.youtube.com/channel/UCfSvDIQ8D_Zz62oAd5mcDDg'
./cfst

record_type="A"     

echo "正在从 Cloudflare 获取 Zone ID..."
# 获取zone_id
cf_response=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$zone_name" \
  -H "X-Auth-Email: $auth_email" \
  -H "X-Auth-Key: $auth_key" \
  -H "Content-Type: application/json")

zone_identifier=$(echo "$cf_response" | grep -Po '(?<="id":")[^"]*' | head -1 )

if [ -z "$zone_identifier" ]; then
    echo "【错误】无法获取 Zone ID！请检查下面的 Cloudflare 返回信息："
    echo "-----------------------------------------------------"
    echo "$cf_response"
    echo "-----------------------------------------------------"
    echo "提示：如果是空的，说明网络连不上CF服务器；如果是 {\"success\":false}，说明你的邮箱或 API Key 填错了。"
    exit 1
fi

sed -n '2,20p' result.csv | while read line
do
    current_domain="$record_name$record_count.$zone_name"
    
    #获取record_id
    record_identifier=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records?name=$current_domain" \
      -H "X-Auth-Email: $auth_email" \
      -H "X-Auth-Key: $auth_key" \
      -H "Content-Type: application/json" | grep -Po '(?<="id":")[^"]*' | head -1 )
    
    if [ -z "$record_identifier" ]; then
        echo "$current_domain 更新失败: 在CF后台找不到该解析记录，请先去CF面板手动创建 A 记录：$current_domain"
        record_count=$(($record_count-1))
        [ $record_count -eq 0 ] && break
        continue
    fi

    #更新DNS记录
    update=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$zone_identifier/dns_records/$record_identifier" \
      -H "X-Auth-Email: $auth_email" \
      -H "X-Auth-Key: $auth_key" \
      -H "Content-Type: application/json" \
      --data "{\"type\":\"$record_type\",\"name\":\"$current_domain\",\"content\":\"${line%%,*}\",\"ttl\":60,\"proxied\":false}")
    
    #反馈更新情况
    if [[ "$update" == *"\"success\":true"* ]]; then
      echo "$current_domain 更新为: ${line%%,*} ....成功"
    else
      echo "$current_domain 更新失败: $update"
    fi

    record_count=$(($record_count-1))    #二级域名序号递减
    if [ $record_count -eq 0 ]; then
        break
    fi
done