#!/bin/bash
set -euo pipefail
UNLOCK_DNS="${UNLOCK_DNS:-${1:-}}"
[ -n "$UNLOCK_DNS" ] || { echo "用法: curl -fsSL https://yt.net/dns-unlock.sh | UNLOCK_DNS=1.2.3.4 bash" >&2; exit 1; }
[ "$(id -u)" = "0" ] || { echo "请用 root 运行" >&2; exit 1; }

if command -v dig >/dev/null 2>&1; then
  probe(){ dig +time=3 +tries=1 +short @"$UNLOCK_DNS" example.com >/dev/null 2>&1; }
elif command -v nslookup >/dev/null 2>&1; then
  probe(){ nslookup -timeout=3 example.com "$UNLOCK_DNS" >/dev/null 2>&1; }
else
  probe(){ return 0; }
fi
probe || { echo "错误: 无法通过 $UNLOCK_DNS 解析, 本机可能到该 DNS 不通, 已中止未修改任何配置。" >&2; exit 1; }

if systemctl is-active --quiet systemd-resolved 2>/dev/null; then
  mkdir -p /etc/systemd/resolved.conf.d
  printf '[Resolve]\nDNS=%s\nDomains=~.\n' "$UNLOCK_DNS" > /etc/systemd/resolved.conf.d/99-yt-unlock.conf
  IFACE=$(ip route | awk '/^default/{print $5; exit}')
  if [ -n "$IFACE" ]; then
    resolvectl dns "$IFACE" "$UNLOCK_DNS" || true
    resolvectl domain "$IFACE" '~.' || true
  fi
  echo "已通过 systemd-resolved 设置 -> $UNLOCK_DNS"
else
  chattr -i /etc/resolv.conf 2>/dev/null || true
  printf 'nameserver %s\n' "$UNLOCK_DNS" > /etc/resolv.conf
  echo "已写入 /etc/resolv.conf -> $UNLOCK_DNS"
fi
echo "完成, 可用 dig baidu.com 验证。"
