最后活跃于 1 month ago

修订 a41721ea57329aeff8df1ee7f08b112d9ff1742b

gistfile1.txt 原始文件
1function cmd::peer::run() {
2 local subcmd="${1:-help}"
3 shift || true
4 case "$subcmd" in
5 update-dns) cmd::peer::update_dns "$@" ;;
6 update-tunnel) cmd::peer::update_tunnel "$@" ;;
7 help) cmd::peer::help ;;
8 *)
9 log::error "Unknown subcommand: '${subcmd}'"
10 cmd::peer::help
11 return 1
12 ;;
13 esac
14}
15
16# ============================================
17# Update DNS
18# ============================================
19
20function cmd::peer::update_dns() {
21 local name="" type="" all=false
22 local dns="" fallback_dns=""
23
24 while [[ $# -gt 0 ]]; do
25 case "$1" in
26 --name) name="$2"; shift 2 ;;
27 --type) type="$2"; shift 2 ;;
28 --all) all=true; shift ;;
29 --dns) dns="$2"; shift 2 ;;
30 --fallback-dns) fallback_dns="$2"; shift 2 ;;
31 --help) cmd::peer::help; return ;;
32 *) log::error "Unknown flag: $1"; return 1 ;;
33 esac
34 done
35
36 [[ -z "$name" && "$all" == "false" ]] && \
37 log::error "Specify --name or --all" && return 1
38
39 # Resolve DNS string
40 local primary="${dns:-$(config::dns)}"
41 local fallback="${fallback_dns:-$(config::dns_fallback)}"
42 local dns_string
43 if [[ -n "$fallback" ]]; then
44 dns_string="${primary}, ${fallback}"
45 else
46 dns_string="$primary"
47 fi
48
49 # Collect target peers
50 local peers=()
51 if $all; then
52 while IFS= read -r conf; do
53 peers+=("$(basename "$conf" .conf)")
54 done < <(find "$(ctx::clients)" -name "*.conf" 2>/dev/null)
55 else
56 name=$(peers::resolve_and_require "$name" "$type") || return 1
57 peers=("$name")
58 fi
59
60 local updated=0
61 for peer_name in "${peers[@]}"; do
62 local conf
63 conf="$(ctx::clients)/${peer_name}.conf"
64 [[ ! -f "$conf" ]] && continue
65
66 # Replace DNS line in-place
67 if grep -q "^DNS" "$conf"; then
68 sed -i "s|^DNS = .*|DNS = ${dns_string}|" "$conf"
69 else
70 # Add DNS line after Address line
71 sed -i "/^Address/a DNS = ${dns_string}" "$conf"
72 fi
73 (( updated++ )) || true
74 log::debug "Updated DNS for: ${peer_name}"
75 done
76
77 log::wg_success "Updated DNS to '${dns_string}' for ${updated} peer(s)"
78}
79