#!/bin/bash

# ====== 配置区 ======
DOMAIN="alytest.cc"
RR="test01"
TYPE="A"
ALIYUN_AK="LTAI5tS54WK4ytx4qEmTBi8c"
ALIYUN_SK="V0MFmTz1xnPRwD0tXEA21a2fyEpUrm"

# ====== 获取公网 IP ======
CURRENT_IP=$(curl -4 -s https://api.ipify.org)
[ -z "$CURRENT_IP" ] && exit 1

# ====== 安装 aliyun cli 后先执行 aliyun configure，可不用每次传密钥 ======
# 这里演示临时环境变量方式
export ALIBABA_CLOUD_ACCESS_KEY_ID="$ALIYUN_AK"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="$ALIYUN_SK"

# ====== 查询当前子域名记录 ======
RECORD_JSON=$(aliyun alidns DescribeSubDomainRecords --SubDomain "${RR}.${DOMAIN}" --output json 2>/dev/null)

RECORD_ID=$(echo "$RECORD_JSON" | jq -r '.DomainRecords.Record[0].RecordId // empty')
OLD_IP=$(echo "$RECORD_JSON" | jq -r '.DomainRecords.Record[0].Value // empty')

# ====== 不存在就新增 ======
if [ -z "$RECORD_ID" ]; then
  aliyun alidns AddDomainRecord \
    --DomainName "$DOMAIN" \
    --RR "$RR" \
    --Type "$TYPE" \
    --Value "$CURRENT_IP"
  echo "已新增解析: ${RR}.${DOMAIN} -> ${CURRENT_IP}"
  exit 0
fi

# ====== IP 相同就不更新 ======
if [ "$OLD_IP" = "$CURRENT_IP" ]; then
  echo "IP 未变化: $CURRENT_IP"
  exit 0
fi

# ====== 更新记录 ======
aliyun alidns UpdateDomainRecord \
  --RecordId "$RECORD_ID" \
  --RR "$RR" \
  --Type "$TYPE" \
  --Value "$CURRENT_IP"

echo "已更新解析: ${RR}.${DOMAIN}  $OLD_IP -> $CURRENT_IP"