64 lines
2.3 KiB
Python
64 lines
2.3 KiB
Python
"""Detect primary nginx site domain on remote Baota/generic hosts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import shlex
|
|
|
|
|
|
def build_nginx_domain_detect_command(*, target_hint: str = "") -> str:
|
|
"""Build remote shell snippet that prints one site hostname to stdout.
|
|
|
|
Lookup order:
|
|
1. Baota vhost basename ``/www/server/panel/vhost/nginx/{domain}.conf``
|
|
2. ``server_name`` in Baota vhosts and generic nginx dirs
|
|
Prefer *target_hint* when it matches a candidate.
|
|
"""
|
|
hint = (target_hint or "").strip().lower()
|
|
qhint = shlex.quote(hint) if hint else "''"
|
|
return (
|
|
f"TARGET_HINT={qhint}; "
|
|
"_is_domain() { "
|
|
'local h="${1,,}"; '
|
|
'[[ "$h" == *.* ]] || return 1; '
|
|
'[[ "$h" =~ ^[0-9]+(\\.[0-9]+){3}$ ]] && return 1; '
|
|
'case "$h" in default|0.default|0.site_total|phpmyadmin|localhost|127.0.0.1|_*|*.local) return 1 ;; esac; '
|
|
"return 0; "
|
|
"}; "
|
|
"_pick() { "
|
|
'local best=""; '
|
|
"for h in \"$@\"; do "
|
|
'[ -n "$h" ] || continue; '
|
|
"_is_domain \"$h\" || continue; "
|
|
'if [ -n "$TARGET_HINT" ] && [ "$h" = "$TARGET_HINT" ]; then echo "$h"; return 0; fi; '
|
|
'if [ -z "$best" ] || [[ "$h" < "$best" ]]; then best="$h"; fi; '
|
|
"done; "
|
|
'[ -n "$best" ] && echo "$best"; '
|
|
"}; "
|
|
"cands=(); "
|
|
'BT="/www/server/panel/vhost/nginx"; '
|
|
'if [ -d "$BT" ]; then '
|
|
'for f in "$BT"/*.conf; do '
|
|
'[ -f "$f" ] || continue; '
|
|
'base=$(basename "$f" .conf); '
|
|
"_is_domain \"$base\" && cands+=(\"$base\"); "
|
|
"done; "
|
|
"fi; "
|
|
'if [ ${#cands[@]} -gt 0 ]; then _pick "${cands[@]}"; exit 0; fi; '
|
|
"_names_from() { "
|
|
'grep -E "^[[:space:]]*server_name[[:space:]]" "$1" 2>/dev/null '
|
|
"| head -1 | sed 's/.*server_name[[:space:]]\\+//;s/;//;s/\\$//g'; "
|
|
"}; "
|
|
'for dir in "$BT" /etc/nginx/sites-enabled /etc/nginx/conf.d; do '
|
|
'[ -d "$dir" ] || continue; '
|
|
'for f in "$dir"/*; do '
|
|
'[ -f "$f" ] || continue; '
|
|
'raw=$(_names_from "$f"); '
|
|
'for token in $raw; do '
|
|
'token="${token,,}"; '
|
|
"_is_domain \"$token\" && cands+=(\"$token\"); "
|
|
"done; "
|
|
"done; "
|
|
"done; "
|
|
'_pick "${cands[@]}"'
|
|
)
|