#!/bin/bash

if [ "$(id -u)" -ne 0 ]; then
    echo "错误：请使用root权限运行此脚本（如 sudo ./fix_github_dns.sh）" >&2
    exit 1
fi

if ! command -v dig &> /dev/null; then
    echo "错误：未找到 'dig' 命令，请安装 dnsutils（Debian/Ubuntu）或 bind-utils（RHEL/CentOS）" >&2
    exit 1
fi

GITHUB_DOMAINS=(
    "github.com"
    "www.github.com"
    "assets-cdn.github.com"
    "raw.githubusercontent.com"
    "gist.github.com"
    "api.github.com"
    "codeload.github.com"
    "github.global.ssl.fastly.net"
)

BACKUP_FILE="/etc/hosts_github_backup_$(date +%Y%m%d%H%M%S)"
cp /etc/hosts "$BACKUP_FILE" || { echo "错误：无法备份 /etc/hosts" >&2; exit 1; }
echo "已备份原hosts文件至：$BACKUP_FILE"

sed -i '/# GitHub DNS Fix Start/,/# GitHub DNS Fix End/d' /etc/hosts

{
    echo
    echo "# GitHub DNS Fix Start"
    for DOMAIN in "${GITHUB_DOMAINS[@]}"; do
        IP=$(dig @114.114.114.114 +short "$DOMAIN" | head -n 1)
        if [ -n "$IP" ]; then
            echo "$IP    $DOMAIN"
            echo "已配置：$IP -> $DOMAIN" >&2
        else
            echo "警告：无法解析 $DOMAIN 的IP，跳过此域名" >&2
        fi
    done
    echo "# GitHub DNS Fix End"
} >> /etc/hosts

if command -v systemd-resolve &> /dev/null && systemctl is-active --quiet systemd-resolved; then
    systemd-resolve --flush-caches &> /dev/null
elif command -v resolvectl &> /dev/null && systemctl is-active --quiet systemd-resolved; then
    resolvectl flush-caches &> /dev/null
fi

echo -e "\nGitHub DNS配置完成！请测试连接（如 ping github.com 或 git clone 仓库）"