#!/usr/bin/env python3
"""
自动配置邮箱服务器 DNS 记录
"""

import os
import sys
import requests
import xml.etree.ElementTree as ET

# 从环境变量读取配置
API_KEY = os.environ.get('NAMESILO_API_KEY', '8cc7145f8d1f3cf4631177d0631077d9deb0ae3f644f21ab6cd23c0c201883ea')
DOMAIN = 'lilexx.top'
SERVER_IP = '192.3.252.113'
MAIL_HOST = f'mail.{DOMAIN}'

def make_request(operation, params=None):
    """发送 API 请求"""
    if params is None:
        params = {}

    params['version'] = '1'
    params['type'] = 'xml'
    params['key'] = API_KEY

    url = f"https://www.namesilo.com/api/{operation}"

    try:
        response = requests.get(url, params=params, timeout=30)
        response.raise_for_status()

        root = ET.fromstring(response.content)

        # 检查响应状态
        reply_code = root.find('.//code')
        if reply_code is not None:
            code = reply_code.text
            detail = root.find('.//detail')
            detail_msg = detail.text if detail is not None else 'No details'

            if code != '300':
                print(f"API Warning (Code {code}): {detail_msg}")
                # 不抛出异常，继续尝试

        return root

    except Exception as e:
        print(f"请求失败: {e}")
        return None

def list_dns_records():
    """列出现有的 DNS 记录"""
    print(f"获取 {DOMAIN} 的 DNS 记录...")
    root = make_request('dnsListRecords', {'domain': DOMAIN})

    if root is None:
        return []

    records = []
    for record in root.findall('.//resource_record'):
        records.append({
            'record_id': record.find('record_id').text if record.find('record_id') is not None else None,
            'type': record.find('type').text if record.find('type') is not None else None,
            'host': record.find('host').text if record.find('host') is not None else None,
            'value': record.find('value').text if record.find('value') is not None else None,
            'ttl': record.find('ttl').text if record.find('ttl') is not None else None,
            'distance': record.find('distance').text if record.find('distance') is not None else None
        })

    return records

def add_dns_record(record_type, host, value, ttl=3600, distance=None):
    """添加 DNS 记录"""
    params = {
        'domain': DOMAIN,
        'rrtype': record_type,
        'rrhost': host,
        'rrvalue': value,
        'rrttl': ttl
    }

    if distance is not None:
        params['rrdistance'] = distance

    print(f"添加 {record_type} 记录: {host} -> {value}")
    root = make_request('dnsAddRecord', params)

    if root is not None:
        record_id = root.find('.//record_id')
        if record_id is not None:
            print(f"  ✓ 成功添加记录 ID: {record_id.text}")
            return record_id.text
        else:
            print(f"  - 记录可能已存在或添加失败")

    return None

def configure_mail_dns():
    """配置邮箱服务器所需的所有 DNS 记录"""
    print("="*60)
    print("开始配置邮箱服务器 DNS 记录")
    print("="*60)
    print()

    # 1. 添加 A 记录 (mail.lilexx.top -> IP)
    print("1. 配置 A 记录 (mail 子域名)")
    add_dns_record('A', 'mail', SERVER_IP)
    print()

    # 2. 添加 MX 记录
    print("2. 配置 MX 记录 (邮件交换)")
    add_dns_record('MX', DOMAIN, MAIL_HOST, distance=10)
    print()

    # 3. 添加 SPF 记录
    print("3. 配置 SPF 记录 (防止邮件伪造)")
    spf_value = f'v=spf1 mx ip4:{SERVER_IP} ~all'
    add_dns_record('TXT', DOMAIN, spf_value)
    print()

    # 4. 添加 DMARC 记录
    print("4. 配置 DMARC 记录 (邮件认证)")
    dmarc_value = f'v=DMARC1; p=none; rua=mailto:postmaster@{DOMAIN}'
    add_dns_record('TXT', '_dmarc', dmarc_value)
    print()

    print("="*60)
    print("DNS 配置完成！")
    print("="*60)
    print()
    print("注意事项：")
    print("1. DNS 记录可能需要几分钟到48小时才能生效")
    print("2. 使用以下命令验证 DNS 配置：")
    print(f"   dig MX {DOMAIN}")
    print(f"   dig A {MAIL_HOST}")
    print(f"   dig TXT {DOMAIN}")
    print()
    print("3. 当前 DNS 记录列表：")
    records = list_dns_records()
    if records:
        for record in records:
            if record.get('type') in ['A', 'MX', 'TXT']:
                print(f"   {record['type']:6} {record['host']:30} -> {record['value']}")
    print()

if __name__ == "__main__":
    configure_mail_dns()
