#!/bin/bash

# 配置区域
SECRET_ID="1254941018"
SECRET_KEY="AKIDDG2XmkRr0tUoreZHjvqUrxsWtzpOghRu"
DOMAIN="dongshan.tech"
SUB_DOMAIN="photo"
API_URL="https://dnspod.tencentcloudapi.com"
IP_FILE=".cf-wan_ip_backup.disbaidu.com.txt"

# 进入脚本所在的目录
cd "$(dirname "$0")"

# 检查 IP 文件是否存在
if [ ! -f "$IP_FILE" ]; then
  echo "文件 $IP_FILE 不存在，请检查。"
  exit 1
fi

# 从文件中读取当前 IP
FILE_IP=$(cat "$IP_FILE" | tr -d '\n')

# 检查文件中的 IP 是否是合法的 IPv4 地址
if [[ ! "$FILE_IP" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
  echo "文件中记录的 IP 地址无效：$FILE_IP"
  exit 1
fi

# 获取域名解析到的现有 IP
DNS_IP=$(ping -c 1 "$SUB_DOMAIN.$DOMAIN" | head -1 | grep -oP '([0-9]{1,3}\.){3}[0-9]{1,3}')

if [ -z "$DNS_IP" ]; then
  echo "无法解析 $SUB_DOMAIN.$DOMAIN，请检查网络或域名配置。"
  exit 1
fi

# 对比 IP，如果一致则退出
if [ "$FILE_IP" == "$DNS_IP" ]; then
  echo "IP 地址未变化，无需更新。"
  exit 0
fi

echo "IP 地址发生变化，文件中的 IP：$FILE_IP，当前解析 IP：$DNS_IP"

# 调用 DNSPod API 修改 DNS 记录
TIMESTAMP=$(date +%s)
NONCE=$RANDOM

# 查询记录的 RecordId
REQUEST_PAYLOAD=$(cat <<EOF
{
    "Domain": "$DOMAIN",
    "Subdomain": "$SUB_DOMAIN"
}
EOF
)

generate_signature() {
  local string_to_sign="$1"
  local signature=$(echo -n "$string_to_sign" | openssl dgst -sha256 -hmac "$SECRET_KEY" -binary | base64)
  echo "$signature"
}

STRING_TO_SIGN="POST\n/\n\ncontent-type:application/json\nhost:dnspod.tencentcloudapi.com\n\ncontent-type;host\n$(echo -n "$REQUEST_PAYLOAD" | openssl dgst -sha256 -binary | base64)"
SIGNATURE=$(generate_signature "$STRING_TO_SIGN")

RECORD_INFO=$(curl -s -X POST "$API_URL" \
  -H "Authorization: TC3-HMAC-SHA256 Credential=$SECRET_ID/$TIMESTAMP, SignedHeaders=content-type;host, Signature=$SIGNATURE" \
  -H "Content-Type: application/json" \
  -d "$REQUEST_PAYLOAD")

RECORD_ID=$(echo "$RECORD_INFO" | jq -r '.Response.RecordList[0].RecordId')

if [ -z "$RECORD_ID" ]; then
  echo "无法获取 RecordId，请检查域名配置。"
  exit 1
fi

# 修改记录
UPDATE_PAYLOAD=$(cat <<EOF
{
    "Domain": "$DOMAIN",
    "SubDomain": "$SUB_DOMAIN",
    "RecordId": "$RECORD_ID",
    "RecordType": "A",
    "RecordLine": "默认",
    "Value": "$FILE_IP"
}
EOF
)

STRING_TO_SIGN="POST\n/\n\ncontent-type:application/json\nhost:dnspod.tencentcloudapi.com\n\ncontent-type;host\n$(echo -n "$UPDATE_PAYLOAD" | openssl dgst -sha256 -binary | base64)"
SIGNATURE=$(generate_signature "$STRING_TO_SIGN")

UPDATE_RESULT=$(curl -s -X POST "$API_URL" \
  -H "Authorization: TC3-HMAC-SHA256 Credential=$SECRET_ID/$TIMESTAMP, SignedHeaders=content-type;host, Signature=$SIGNATURE" \
  -H "Content-Type: application/json" \
  -d "$UPDATE_PAYLOAD")

UPDATE_STATUS=$(echo "$UPDATE_RESULT" | jq -r '.Response.RequestId')

if [ "$UPDATE_STATUS" ]; then
  echo "DNS 记录更新成功，新 IP：$FILE_IP"
else
  echo "DNS 记录更新失败，请检查日志：$UPDATE_RESULT"
fi
