#!/usr/bin/env bash
# VLESS Wiki: 3x-ui + XHTTP + Vision (VLESS Encryption), TLS or REALITY/self-SNI.
set -Eeuo pipefail
umask 077

usage() {
  cat <<'EOF'
VLESS Wiki — установка на чистый Ubuntu 22.04/24.04 или Debian 12/13.
  sudo bash install.sh --domain vpn.example.com
  sudo bash install.sh                         # спросит домен
Параметры:
  -d, --domain ДОМЕН    одна A-запись на публичный IPv4 этого сервера
  --mode tls|reality    выбрать режим без меню (Reality требует минимум два IPv4)
  --resume              продолжить незавершённую установку с сертификата или nginx
  --resume --domain ДОМЕН  продолжить с новым доменом, сохранив панель и доступы
  -h, --help            справка
Сначала обновляется система, затем проверяются IP и DNS, выбирается режим.
IPv6 обнаруживается, но установка использует публичные IPv4 без NAT.
XHTTP + Vision требует клиента с поддержкой VLESS Encryption.
Существующие установки Xray/3x-ui не перезаписываются.
EOF
}
C_RED='' C_GREEN='' C_BLUE='' C_YELLOW='' C_BOLD='' C_RESET=''
init_colors() {
  if [[ -z "${NO_COLOR+x}" && ( -t 1 || "${FORCE_COLOR:-0}" == 1 ) && "${TERM:-}" != dumb ]]; then
    C_RED=$'\033[1;31m'; C_GREEN=$'\033[1;32m'; C_BLUE=$'\033[1;36m'
    C_YELLOW=$'\033[1;33m'; C_BOLD=$'\033[1m'; C_RESET=$'\033[0m'
  else
    C_RED='' C_GREEN='' C_BLUE='' C_YELLOW='' C_BOLD='' C_RESET=''
  fi
}
paint() { printf '%s%s%s\n' "$1" "$2" "$C_RESET"; }
step() { STEP=$((STEP + 1)); printf '\n'; paint "$C_BLUE" "[$STEP] $*"; }
die() { printf '\n' >&2; paint "$C_RED" "ОШИБКА: $*" >&2; exit 1; }
mode_option() {
  local color="$C_RED" status='НЕДОСТУПНО'
  if [[ "$1" == yes ]]; then color="$C_GREEN"; status='ДОСТУПНО'; fi
  if [[ "$1" == yellow ]]; then color="$C_YELLOW"; status='ДОСТУПНО: используется только один IP'; fi
  paint "$color" "$2 — $status"
  printf '   %s\n' "$3"
  [[ "$1" != no ]] || paint "$C_RED" "   $4"
  printf '\n'
}
show_modes() {
  local count="$1" single=no dual=no
  if [[ "$count" == 1 ]]; then single=yes; else single=yellow; dual=yes; fi
  printf '\n'
  paint "$C_BOLD" "Обнаружено публичных IPv4: $count"
  paint "$C_BLUE" 'Зелёный — доступно. Жёлтый — доступно, но второй IP не используется. Красный — недоступно.'
  printf '\n'
  mode_option "$single" '1) Один IP: VLESS + XHTTP + TLS + Vision' \
    'Один IP для входа и выхода. Если есть второй IP, он не используется. Обычный TLS с сертификатом твоего домена; HTTPS принимает nginx.' \
    'Нужен хотя бы один публичный IPv4.'
  mode_option "$dual" '2) Два IP: VLESS + XHTTP + TLS + Vision' \
    'Как пункт 1, но вход идёт через IP домена, а выход в интернет — через второй IP. Внешний TLS принимает nginx.' \
    'Нужны минимум два публичных IPv4. Сейчас доступен только пункт 1.'
  mode_option "$dual" '3) Два IP: VLESS + XHTTP + Reality + self-SNI + Vision' \
    'VPN использует Reality вместо обычного TLS. SNI — твой домен, цель Reality — локальный nginx. Вход через IP домена, выход через второй IP.' \
    'Нужны минимум два публичных IPv4. Сейчас доступен только пункт 1.'
  printf '   В пункте 3 сертификат всё равно нужен для сайта и панели.\n'
  printf '   Во всех пунктах: XHTTP + Vision с VLESS Encryption. Нужен совместимый VPN-клиент.\n'
  printf '   TLS (1/2) — если хочешь обычное HTTPS-подключение к своему домену.\n'
  printf '   Reality (3) — если хочешь использовать Reality с собственным SNI и клиент это поддерживает.\n'
  printf '\n'
  paint "$C_BOLD" '0) Выход'
}
fetch() { curl -fsSL --retry 3 --connect-timeout 15 --max-time 180 "$1" -o "$2"; }
fetch_dns() {
  curl -fsSL --retry 3 --connect-timeout 15 --max-time 30 \
    -H 'accept: application/dns-json' --get \
    --data-urlencode "name=$DOMAIN" --data-urlencode "type=$1" \
    'https://cloudflare-dns.com/dns-query' -o "$2"
}
report_failure() {
  printf '\n' >&2
  paint "$C_RED" "Установка остановлена: строка $1, шаг $STEP. Проверь ошибку выше." >&2
  if [[ -d /root/vless-wiki ]]; then
    printf 'Данные установки: /root/vless-wiki.\n' >&2
  fi
  if [[ -x /usr/local/x-ui/x-ui ]]; then
    printf 'Журнал 3x-ui: journalctl -u x-ui -n 50 --no-pager\n' >&2
  else
    printf '3x-ui ещё не установлен, его журнал пока пуст.\n' >&2
  fi
}
ask() { IFS= read -r -p "$1" "$2" </dev/tty || die 'Не удалось прочитать ответ. Используй --domain и --mode.'; }

core() {
  python3 - "$@" <<'PY_CORE'
import ipaddress
import json
import os
from pathlib import Path
import re
import secrets
import socket
import subprocess
import sys
import time
import tempfile
from urllib.parse import quote, urlencode, urlsplit, parse_qs
from urllib.request import Request, urlopen


def read(path):
    return json.loads(Path(path).read_text())


def write(path, value):
    path = Path(path)
    temporary = path.with_suffix('.tmp')
    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n')
    temporary.chmod(0o600)
    temporary.replace(path)


def normalize_domain(value):
    domain = value.strip().lower().rstrip('.')
    if len(domain) > 253 or not re.fullmatch(r'(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}', domain):
        raise ValueError('Укажи домен без https://, порта и пути, например vpn.example.com (IDN — в punycode).')
    return domain


def inventory(addresses, dns_a, dns_aaaa):
    all_ips = sorted({a['local'] for interface in addresses for a in interface.get('addr_info', [])
                      if a.get('scope') == 'global' and 'local' in a})
    public = sorted({ip for ip in all_ips if ipaddress.ip_address(ip).version == 4
                     and ipaddress.ip_address(ip).is_global}, key=ipaddress.ip_address)
    if not public:
        raise ValueError('На интерфейсах нет публичного IPv4. NAT и floating IP без локальной привязки не поддерживаются.')
    if dns_a.get('Status') != 0 or dns_aaaa.get('Status') != 0:
        raise ValueError('DNS-запрос не завершился успешно. Проверь домен и DNS.')
    resolved = sorted({a['data'] for a in dns_a.get('Answer', []) if a.get('type') == 1})
    if len(resolved) != 1 or resolved[0] not in public:
        raise ValueError('Нужна одна A-запись на публичный IPv4 этого сервера. Сейчас: ' + ', '.join(resolved))
    if any(a.get('type') == 28 for a in dns_aaaa.get('Answer', [])):
        raise ValueError('У домена есть AAAA-запись. Удали её: эта установка использует только IPv4.')
    inbound = resolved[0]
    extra = [ip for ip in public if ip != inbound]
    return dict(all_ips=all_ips, public_ipv4=public, inbound_ip=inbound,
                outbound_ip=extra[0] if extra else inbound,
                available=['tls-single'] if len(public) == 1 else ['tls-single', 'tls-dual', 'reality-dual'])


def select_profile(plan, choice):
    aliases = {'1': 'tls-single', '2': 'tls-dual', '3': 'reality-dual'}
    if choice == 'tls':
        choice = 'tls-single' if len(plan['public_ipv4']) == 1 else 'tls-dual'
    elif choice == 'reality':
        choice = 'reality-dual'
    choice = aliases.get(choice, choice)
    if choice not in plan['available']:
        raise ValueError('Этот вариант недоступен при обнаруженном количестве публичных IPv4.')
    return choice


def profile_outbound(plan, profile):
    profile = select_profile(plan, profile)
    return plan['inbound_ip'] if profile == 'tls-single' else plan['outbound_ip']


def free_ports(count):
    sockets = []
    try:
        for _ in range(count):
            s = socket.socket()
            s.bind(('127.0.0.1', 0))
            sockets.append(s)
        return [s.getsockname()[1] for s in sockets]
    finally:
        for s in sockets:
            s.close()


def keypairs(binary):
    output = subprocess.check_output([binary, 'vlessenc'], text=True)
    dec = re.search(r'"decryption"\s*:\s*"([^"]+)"', output)
    enc = re.search(r'"encryption"\s*:\s*"([^"]+)"', output)
    if not dec or not enc:
        raise ValueError('Xray не поддерживает VLESS Encryption, необходимый для XHTTP + Vision.')
    return dec[1], enc[1]


def api(state, method, path, data=None):
    token = os.environ.get('XUI_API_TOKEN', '')
    if not token:
        raise ValueError('Нет API-токена 3x-ui в /etc/x-ui/install-result.env.')
    req = Request(f"http://127.0.0.1:{state['panel_port']}/{state['web_path']}/panel/api{path}",
                  data=None if data is None else json.dumps(data).encode(), method=method,
                  headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'})
    with urlopen(req, timeout=20) as response:
        result = json.load(response)
    if result.get('success') is not True:
        raise ValueError(f"3x-ui API {path}: {result.get('msg', 'ошибка')}")
    return result.get('obj')


def nginx_config(s, bootstrap=False):
    domain, inbound = s['domain'], s['inbound_ip']
    common = f'''server {{
    listen {inbound}:80;
    server_name {domain};
    location ^~ /.well-known/acme-challenge/ {{
        root /var/www/acme;
        default_type text/plain;
        auth_basic off;
        allow all;
        try_files $uri =404;
    }}
    location / {{ return 301 https://{domain}$request_uri; }}
}}
'''
    if bootstrap:
        return common
    listener = f"127.0.0.1:{s['site_port']} ssl http2 proxy_protocol" if s['mode'] == 'reality' else f'{inbound}:443 ssl http2'
    realip = 'set_real_ip_from 127.0.0.1; real_ip_header proxy_protocol;' if s['mode'] == 'reality' else ''
    xhttp = '' if s['mode'] == 'reality' else f'''
    location ^~ {s['xhttp_path']} {{
        proxy_pass http://127.0.0.1:{s['xhttp_port']};
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_request_buffering off;
        client_max_body_size 0;
        proxy_read_timeout 3600s;
        proxy_send_timeout 3600s;
    }}
'''
    default_tls = 'ssl_reject_handshake on;' if s.get('nginx_reject_handshake', True) else (
        'ssl_certificate /root/vless-wiki/default-tls.crt;\n'
        '    ssl_certificate_key /root/vless-wiki/default-tls.key;\n'
        '    return 444;')
    return common + f'''server {{
    listen {listener} default_server;
    server_name _;
    ssl_protocols TLSv1.2 TLSv1.3;
    {default_tls}
}}
server {{
    listen {listener};
    server_name {domain};
    ssl_certificate {s['cert_dir']}/fullchain.pem;
    ssl_certificate_key {s['cert_dir']}/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    server_tokens off;
    absolute_redirect off;
    {realip}
    root {s['site_dir']};
    index index.html;
    location /{s['web_path']}/ {{
        proxy_pass http://127.0.0.1:{s['panel_port']};
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 3600s;
    }}
    location /{s['sub_path']}/ {{
        proxy_pass http://127.0.0.1:{s['sub_port']};
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-Proto https;
    }}
{xhttp}
    location / {{ return 404; }}
}}
'''


def inbound_config(s):
    stream = {'network': 'xhttp', 'security': 'none',
              'xhttpSettings': {'path': s['xhttp_path'], 'mode': 'packet-up'}}
    listen, port = '127.0.0.1', s['xhttp_port']
    if s['mode'] == 'reality':
        listen, port = s['inbound_ip'], 443
        stream.update(security='reality', realitySettings={
            'show': False, 'target': f"127.0.0.1:{s['site_port']}", 'xver': 1,
            'serverNames': [s['domain']], 'privateKey': s['reality_private'],
            'shortIds': [s['short_id']],
            'settings': {'publicKey': s['reality_public'], 'fingerprint': 'firefox', 'spiderX': '/'}})
    return {'enable': True, 'remark': 'VLESS-XHTTP-' + s['mode'].upper(),
            'listen': listen, 'port': port, 'protocol': 'vless', 'expiryTime': 0, 'total': 0,
            'shareAddrStrategy': 'custom', 'shareAddr': s['domain'],
            'settings': {'clients': [], 'decryption': s['decryption'], 'encryption': s['encryption']},
            'streamSettings': stream,
            'sniffing': {'enabled': True, 'destOverride': ['http', 'tls'], 'routeOnly': True}}


def client_config(link, port):
    u = urlsplit(link)
    q = {k: v[0] for k, v in parse_qs(u.query).items()}
    stream = {'network': q['type'], 'security': q['security'],
              'xhttpSettings': {'path': q['path'], 'mode': q['mode'], 'host': q['host']}}
    if q['security'] == 'reality':
        stream['realitySettings'] = {'serverName': q['sni'], 'fingerprint': q['fp'],
                                     'publicKey': q['pbk'], 'shortId': q['sid']}
    else:
        stream['tlsSettings'] = {'serverName': q['sni'], 'fingerprint': q['fp'], 'alpn': ['h2', 'http/1.1']}
    return {'log': {'loglevel': 'warning'},
            'inbounds': [{'listen': '127.0.0.1', 'port': port, 'protocol': 'socks', 'settings': {'auth': 'noauth', 'udp': False}}],
            'outbounds': [{'protocol': 'vless', 'settings': {'vnext': [{'address': u.hostname, 'port': u.port,
                'users': [{'id': u.username, 'encryption': q['encryption'], 'flow': q['flow']}]}]}, 'streamSettings': stream}]}


def make_link(s, client):
    # ClientRecord API uses numeric id for the database row and uuid for VLESS.
    # Older inline-client payloads keep the VLESS identity in string id.
    identity = client.get('uuid') or client.get('id')
    if not isinstance(identity, str) or not identity.strip():
        raise ValueError('API не вернул UUID VLESS-клиента; числовой ID записи использовать нельзя.')
    q = dict(encryption=s['encryption'], flow='xtls-rprx-vision', type='xhttp',
             security=s['mode'], sni=s['domain'], fp='firefox',
             path=s['xhttp_path'], mode='packet-up', host=s['domain'])
    if s['mode'] == 'reality':
        q.update(pbk=s['reality_public'], sid=s['short_id'])
    else:
        q['alpn'] = 'h2,http/1.1'
    return f"vless://{identity}@{s['domain']}:443?{urlencode(q)}#{quote('VLESS-XHTTP-' + s['mode'].upper())}"


RU_BLOCK_TAG = 'vless-wiki-block-ru'


def ru_block_template(template):
    if isinstance(template, str): template = json.loads(template)
    # Work on a copy so failed validation cannot change the caller's original value.
    template = json.loads(json.dumps(template))
    if not isinstance(template, dict) or not isinstance(template.get('outbounds'), list):
        raise ValueError('Некорректный шаблон Xray в 3x-ui.')
    found = [o for o in template['outbounds'] if o.get('tag') == RU_BLOCK_TAG]
    if found and (len(found) != 1 or found[0].get('protocol') != 'blackhole'):
        raise ValueError('Тег блокировки РФ занят другим outbound.')
    if not found: template['outbounds'].append({'tag': RU_BLOCK_TAG, 'protocol': 'blackhole'})
    routing = template.setdefault('routing', {})
    if routing.get('script'):
        raise ValueError('В панели используется routing.script. Автоматическая замена его логики остановлена.')
    # Resolve domain destinations before IP-based rules, even if a catch-all follows.
    routing['domainStrategy'] = 'IPOnDemand'
    managed_tags = {'vless-wiki-ru-domains', 'vless-wiki-ru-ip'}
    rules = [r for r in routing.get('rules', []) if r.get('ruleTag') not in managed_tags]
    control = [r for r in rules if r.get('outboundTag') == 'api']
    other = [r for r in rules if r.get('outboundTag') != 'api']
    block = [
        {'type': 'field', 'ruleTag': 'vless-wiki-ru-domains',
         'domain': ['geosite:category-ru', 'domain:ru', 'domain:su', 'domain:xn--p1ai'], 'outboundTag': RU_BLOCK_TAG},
        {'type': 'field', 'ruleTag': 'vless-wiki-ru-ip', 'ip': ['geoip:ru'], 'outboundTag': RU_BLOCK_TAG},
    ]
    routing['rules'] = control + block + other
    return template


def validate_xray_template(s, template):
    binary = Path(s['xray_binary'])
    with tempfile.TemporaryDirectory(prefix='vless-routing-') as directory:
        path = Path(directory) / 'config.json'
        write(path, template)
        result = subprocess.run([str(binary), 'run', '-test', '-c', str(path)],
                                env={**os.environ, 'XRAY_LOCATION_ASSET': str(binary.parent)},
                                capture_output=True, text=True)
        if result.returncode != 0:
            raise ValueError('Xray не принял правила РФ (проверь geoip.dat/geosite.dat в папке bin): ' +
                             result.stdout + result.stderr)


def apply_ru_block(state_path, db_path='/etc/x-ui/x-ui.db'):
    import sqlite3
    from contextlib import closing
    s = read(state_path)
    with closing(sqlite3.connect(db_path)) as db:
        row = db.execute('SELECT value FROM settings WHERE key=?', ('xrayTemplateConfig',)).fetchone()
    previous = row[0] if row else None
    current = json.loads(previous) if previous else api(s, 'GET', '/xray/getDefaultJsonConfig')
    if isinstance(current, str): current = json.loads(current)
    candidate = ru_block_template(current)
    validate_xray_template(s, candidate)
    if candidate == current:
        print('Блокировка РФ уже включена: geoip:ru, category-ru, .ru, .su, .рф.')
        return
    backup = Path(state_path).with_name('routing.before-ru-block.' + secrets.token_hex(6) + '.json')
    write(backup, {'xrayTemplateConfig': previous})
    subprocess.run(['systemctl', 'stop', 'x-ui'], check=True)
    def save(value):
        with closing(sqlite3.connect(db_path)) as db, db:
            if value is None:
                db.execute('DELETE FROM settings WHERE key=?', ('xrayTemplateConfig',))
            elif db.execute('SELECT 1 FROM settings WHERE key=?', ('xrayTemplateConfig',)).fetchone():
                db.execute('UPDATE settings SET value=? WHERE key=?', (value, 'xrayTemplateConfig'))
            else:
                db.execute('INSERT INTO settings(key,value) VALUES(?,?)', ('xrayTemplateConfig', value))
    try:
        save(json.dumps(candidate))
        subprocess.run(['systemctl', 'start', 'x-ui'], check=True)
        wait_panel(s)
    except Exception:
        subprocess.run(['systemctl', 'stop', 'x-ui'], check=False)
        save(previous)
        subprocess.run(['systemctl', 'start', 'x-ui'], check=True)
        raise ValueError('Не удалось применить блокировку РФ; прежние настройки маршрутизации восстановлены.')
    print('3x-ui: трафик к российским IP и доменам направляется в blackhole. Резервная копия: ' + str(backup))


def template_config(template, outbound):
    if isinstance(template, str):
        template = json.loads(template)
    if not isinstance(template, dict) or not isinstance(template.get('outbounds'), list):
        raise ValueError('3x-ui вернул неизвестный формат шаблона Xray.')
    freedoms = [o for o in template['outbounds'] if o.get('protocol') == 'freedom']
    if not freedoms:
        raise ValueError('В шаблоне 3x-ui нет выхода freedom.')
    for out in freedoms:
        out['sendThrough'] = outbound
        # Both destinations and DNS resolutions use IPv4 for an IPv4-bound egress.
        out.setdefault('settings', {})['domainStrategy'] = 'UseIPv4'
    return ru_block_template(template)


def provision(state_path):
    s = read(state_path)
    s['decryption'], s['encryption'] = keypairs(s['xray_binary'])
    if s['mode'] == 'reality':
        keys = subprocess.check_output([s['xray_binary'], 'x25519'], text=True)
        private = re.search(r'^Private\s*Key:\s*(\S+)', keys, re.M | re.I)
        public = re.search(r'^(?:Public\s*Key|Password(?: \(PublicKey\))?):\s*(\S+)', keys, re.M | re.I)
        if not private or not public:
            raise ValueError('Не удалось разобрать ключи Reality.')
        s.update(reality_private=private[1], reality_public=public[1])
    write(state_path, s)
    # Panel owns generated Xray configuration; set its template through its SQLite settings.
    template = template_config(api(s, 'GET', '/xray/getDefaultJsonConfig'), s['outbound_ip'])
    validate_xray_template(s, template)
    subprocess.run(['systemctl', 'stop', 'x-ui'], check=True)
    import sqlite3
    from contextlib import closing
    try:
        with closing(sqlite3.connect('/etc/x-ui/x-ui.db')) as db, db:
            values = {'xrayTemplateConfig': json.dumps(template), 'webListen': '127.0.0.1',
                      'subEnable': 'true', 'subListen': '127.0.0.1', 'subPort': str(s['sub_port']),
                      'subPath': f"/{s['sub_path']}/", 'subURI': f"https://{s['domain']}/{s['sub_path']}/",
                      'webCertFile': '', 'webKeyFile': '', 'subCertFile': '', 'subKeyFile': ''}
            for k, v in values.items():
                if db.execute('SELECT 1 FROM settings WHERE key=?', (k,)).fetchone():
                    db.execute('UPDATE settings SET value=? WHERE key=?', (v, k))
                else:
                    db.execute('INSERT INTO settings(key,value) VALUES(?,?)', (k, v))
    finally:
        subprocess.run(['systemctl', 'start', 'x-ui'], check=True)
    wait_panel(s)
    inbound = api(s, 'POST', '/inbounds/add', inbound_config(s))
    if not isinstance(inbound, dict) or not inbound.get('id'):
        raise ValueError('API не вернул ID созданного inbound.')
    s['inbound_id'] = inbound['id']
    write(state_path, s)
    # Describe the public nginx endpoint so panel exports and subscriptions use 443/TLS.
    api(s, 'POST', '/hosts/add', {'inboundIds': [inbound['id']], 'remark': 'Public endpoint',
                                 'hosts': [s['domain']], 'port': 443, 'security': s['mode'],
                                 'sni': s['domain'], 'hostHeader': s['domain'],
                                 'path': s['xhttp_path'], 'fingerprint': 'firefox',
                                 'alpn': ['h2', 'http/1.1']})
    api(s, 'POST', '/clients/add', {'client': {'email': 'user1', 'flow': 'xtls-rprx-vision',
                                            'enable': True, 'limitIp': 0, 'totalGB': 0, 'expiryTime': 0},
                                  'inboundIds': [inbound['id']]})
    data = api(s, 'GET', '/clients/get/user1')
    client = data.get('client', data)
    s['vless_link'] = make_link(s, client)
    s['subscription_url'] = f"https://{s['domain']}/{s['sub_path']}/{client['subId']}"
    s['panel_url'] = f"https://{s['domain']}/{s['web_path']}/"
    write(state_path, s)
    subprocess.run(['systemctl', 'restart', 'x-ui'], check=True)
    wait_panel(s)


def wait_panel(s):
    for _ in range(30):
        try:
            api(s, 'GET', '/inbounds/list')
            return
        except Exception:
            time.sleep(2)
    raise ValueError('3x-ui API не отвечает. Проверь journalctl -u x-ui.')


def selftest(s, directory):
    directory = Path(directory)
    port = free_ports(1)[0]
    config_path = directory / 'test-client.json'
    log_path = directory / 'test-client.log'
    write(config_path, client_config(s['vless_link'], port))
    binary = s['xray_binary']
    process = None
    try:
        subprocess.run([binary, 'run', '-test', '-c', str(config_path)], check=True, capture_output=True)
        with log_path.open('w') as log:
            log_path.chmod(0o600)
            process = subprocess.Popen([binary, 'run', '-c', str(config_path)], stdout=log, stderr=log)
            ready = False
            for _ in range(60):
                if process.poll() is not None:
                    break
                try:
                    with socket.create_connection(('127.0.0.1', port), timeout=.2):
                        ready = True
                        break
                except OSError:
                    time.sleep(.2)
            if not ready:
                raise ValueError('Тестовый Xray-клиент не запустился: ' + str(log_path))
            errors = []
            for url in ('https://api.ipify.org', 'https://ifconfig.me/ip'):
                result = subprocess.run(['curl', '-4', '-fsS', '--noproxy', '', '--max-time', '20',
                                         '--socks5-hostname', f'127.0.0.1:{port}', url], capture_output=True, text=True)
                actual = result.stdout.strip()
                if result.returncode == 0 and actual == s['outbound_ip']:
                    print('OK: готовая VLESS-ссылка работает, выходящий IPv4: ' + actual)
                    return
                errors.append(f'{url}: код {result.returncode}, IP {actual!r}')
            raise ValueError('Самотест не прошёл: ' + '; '.join(errors) + '. Лог: ' + str(log_path))
    finally:
        if process is not None:
            process.terminate()
            try:
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
                process.wait()
        config_path.unlink(missing_ok=True)


def change_pending_domain(state_path, domain, plan):
    s = read(state_path)
    domain = normalize_domain(domain)
    if domain != s['domain'] and any(s.get(k) for k in ('inbound_id', 'vless_link', 'panel_url')):
        raise ValueError('VPN уже настраивался. Смена домена на этом этапе не поддерживается.')
    if (plan['inbound_ip'], profile_outbound(plan, s['profile'])) != (s['inbound_ip'], s['outbound_ip']):
        raise ValueError('Новый домен должен указывать на прежний входящий IPv4; выходящий IP тоже должен остаться доступен.')
    select_profile(plan, s['profile'])
    if domain == s['domain']:
        return
    backup = Path(state_path).with_name('state.before-domain-change.' + secrets.token_hex(6) + '.json')
    write(backup, s)
    old = s['domain']
    s.update(domain=domain, cert_dir='/root/cert/' + domain, site_dir='/var/www/' + domain)
    write(state_path, s)
    print(f'Домен изменён: {old} → {domain}. Предыдущие параметры: {backup}')


def resume_stage(s):
    keys = ('inbound_id', 'vless_link', 'panel_url', 'subscription_url')
    if all(s.get(k) for k in keys):
        return 'nginx'
    if any(s.get(k) for k in keys):
        raise ValueError('Настройка VPN прервалась в середине шага. Нужна проверка перед продолжением.')
    return 'certificate'


def nginx_supports_reject(version):
    match = re.search(r'nginx/(\d+)\.(\d+)\.(\d+)', version)
    return bool(match and tuple(map(int, match.groups())) >= (1, 19, 4))


def verify_provisioned_inbound(s, listed):
    if not isinstance(listed, list) or len(listed) != 1 or listed[0].get('id') != s['inbound_id']:
        raise ValueError('Подключения панели отличаются от сохранённой установки. Продолжение остановлено.')
    actual = api(s, 'GET', f"/inbounds/get/{s['inbound_id']}")
    expected = inbound_config(s)
    for key in ('port', 'listen', 'protocol'):
        if actual.get(key) != expected[key]:
            raise ValueError('Изменены параметры существующего подключения: ' + key)
    settings = actual.get('settings', {})
    stream = actual.get('streamSettings', {})
    if isinstance(settings, str): settings = json.loads(settings)
    if isinstance(stream, str): stream = json.loads(stream)
    if settings.get('decryption') != s['decryption'] or stream.get('network') != 'xhttp':
        raise ValueError('Параметры XHTTP/VLESS не совпадают с сохранёнными.')
    if stream.get('xhttpSettings', {}).get('path') != s['xhttp_path']:
        raise ValueError('Путь XHTTP изменён.')
    if stream.get('security') != expected['streamSettings']['security']:
        raise ValueError('Режим защиты подключения изменён.')
    if s['mode'] == 'reality':
        r = stream.get('realitySettings', {})
        if r.get('privateKey') != s['reality_private'] or r.get('serverNames') != [s['domain']]:
            raise ValueError('Настройки Reality изменены.')
    identity = urlsplit(s['vless_link']).username
    clients = settings.get('clients', [])
    if any(c.get('id') == identity and c.get('flow') == 'xtls-rprx-vision' for c in clients):
        return None
    # Repair only this installer's old numeric-record-id bug, never arbitrary mismatches.
    data = api(s, 'GET', '/clients/get/user1')
    client = data.get('client', {}) if isinstance(data, dict) else {}
    real_uuid = client.get('uuid')
    is_known_bug = (type(client.get('id')) is int and identity == str(client['id'])
                    and client.get('email') == 'user1'
                    and s['inbound_id'] in data.get('inboundIds', [])
                    and isinstance(real_uuid, str) and real_uuid
                    and client.get('flow') == 'xtls-rprx-vision'
                    and any(c.get('id') == real_uuid and c.get('flow') == 'xtls-rprx-vision' for c in clients))
    if not is_known_bug or s['vless_link'] != make_link(s, {'id': identity}):
        raise ValueError('UUID/flow клиента панели не совпадают с сохранённой ссылкой; автоматическая замена запрещена.')
    return make_link(s, client)


def acme_failure(log):
    if 'urn:ietf:params:acme:error:rateLimited' in log:
        text = 'Let’s Encrypt ограничил выпуск сертификатов.'
        if 'exact set of identifiers' in log:
            text += ' Достигнут лимит для этого набора доменных имён.'
        retry = re.search(r'retry after (\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC)', log)
        if retry:
            text += '\nПовтори bash install.sh --resume после ' + retry[1] + '.'
        else:
            text += '\nВремя повторной попытки смотри в /root/vless-wiki/acme.log.'
        return text + '\nЭтот отказ получен от CA до проверки порта 80; он не свидетельствует об ошибке UFW.'
    return ('Не удалось выпустить сертификат. Последние строки журнала:\n' +
            '\n'.join(log.splitlines()[-20:]) +
            '\nПолный журнал: /root/vless-wiki/acme.log.')


def main():
    cmd, *args = sys.argv[1:]
    if cmd == 'domain':
        print(normalize_domain(args[0]))
    elif cmd == 'inventory':
        print(json.dumps(inventory(*(read(p) for p in args)), ensure_ascii=False))
    elif cmd == 'get':
        value = read(args[0])[args[1]]
        print('\n'.join(map(str, value)) if isinstance(value, list) else value)
    elif cmd == 'select':
        print(select_profile(read(args[0]), args[1]))
    elif cmd == 'profile-outbound':
        print(profile_outbound(read(args[0]), args[1]))
    elif cmd == 'init':
        plan_path, path, domain, profile = args
        s = read(plan_path)
        s.update(domain=normalize_domain(domain), profile=select_profile(s, profile))
        s['outbound_ip'] = profile_outbound(s, s['profile'])
        s['mode'] = 'reality' if s['profile'] == 'reality-dual' else 'tls'
        ports = free_ports(4)
        s.update(panel_port=ports[0], sub_port=ports[1], site_port=ports[2], xhttp_port=ports[3],
                 web_path=secrets.token_hex(16), sub_path=secrets.token_hex(16),
                 xhttp_path='/' + secrets.token_hex(16) + '/', short_id=secrets.token_hex(8),
                 username=secrets.token_hex(6), password=secrets.token_urlsafe(24),
                 cert_dir='/root/cert/' + domain, site_dir='/var/www/' + domain)
        write(path, s)
    elif cmd == 'nginx':
        print(nginx_config(read(args[0]), len(args) > 1 and args[1] == 'bootstrap'))
    elif cmd == 'nginx-compat':
        result = subprocess.run(['nginx', '-v'], capture_output=True, text=True, check=True)
        s = read(args[0])
        s['nginx_reject_handshake'] = nginx_supports_reject(result.stdout + result.stderr)
        write(args[0], s)
        print('native' if s['nginx_reject_handshake'] else 'legacy')
    elif cmd == 'resume-stage':
        print(resume_stage(read(args[0])))
    elif cmd == 'set-binary':
        s = read(args[0]); s['xray_binary'] = args[1]; write(args[0], s)
    elif cmd == 'wait':
        wait_panel(read(args[0]))
    elif cmd == 'block-ru':
        apply_ru_block(args[0])
    elif cmd == 'provision':
        provision(args[0])
    elif cmd == 'selftest':
        selftest(read(args[0]), args[1])
    elif cmd == 'check-subscription':
        import base64
        s, body = read(args[0]), Path(args[1]).read_text().strip()
        if not body.startswith('vless://'):
            body = base64.b64decode(body + '=' * (-len(body) % 4)).decode()
        expected = urlsplit(s['vless_link'])
        expected_q = parse_qs(expected.query)
        for line in body.splitlines():
            if not line.startswith('vless://'): continue
            u = urlsplit(line); q = parse_qs(u.query)
            if (u.hostname, u.port, u.username) != (expected.hostname, expected.port, expected.username): continue
            if all(q.get(k) == expected_q.get(k) for k in ('type', 'security', 'encryption', 'flow', 'path', 'sni', 'mode')):
                if s['mode'] != 'reality' or all(q.get(k) == expected_q.get(k) for k in ('pbk', 'sid')):
                    print('OK: подписка содержит правильный публичный VLESS-профиль')
                    return
        raise ValueError('Подписка 3x-ui не содержит ожидаемый VLESS-профиль на публичном порту 443.')
    elif cmd == 'change-domain':
        change_pending_domain(args[0], args[1], read(args[2]))
    elif cmd == 'acme-error':
        print(acme_failure(Path(args[0]).read_text(errors='replace')))
    elif cmd == 'resume-check':
        s = read(args[0])
        normalize_domain(s['domain'])
        required = ('inbound_ip', 'outbound_ip', 'panel_port', 'web_path', 'sub_path', 'sub_port',
                    'xhttp_path', 'xhttp_port', 'site_port', 'username', 'password', 'mode', 'profile')
        if any(k not in s for k in required):
            raise ValueError('Неполные данные предыдущей установки; продолжение остановлено.')
        stage = resume_stage(s)
        if os.environ.get('XUI_USERNAME') != s['username'] or os.environ.get('XUI_PASSWORD') != s['password']:
            raise ValueError('Доступы панели не совпадают с сохранёнными. Продолжение остановлено.')
        if str(s['panel_port']) != os.environ.get('XUI_PANEL_PORT', ''):
            raise ValueError('Порт панели не совпадает с сохранённым.')
        listed = api(s, 'GET', '/inbounds/list')
        if stage == 'nginx':
            repaired_link = verify_provisioned_inbound(s, listed)
            if repaired_link:
                backup = Path(args[0]).with_name('state.before-link-repair.' + secrets.token_hex(6) + '.json')
                write(backup, s)
                s['vless_link'] = repaired_link
                write(args[0], s)
                print('Исправлена сохранённая ссылка: использован UUID клиента вместо числового ID записи. Клиент и ключи не изменены.')
                print('Предыдущие параметры: ' + str(backup))
        elif listed != []:
            raise ValueError('В панели уже есть подключения. Автоматическое продолжение остановлено.')
        if s.get('cert_dir') != '/root/cert/' + s['domain'] or s.get('site_dir') != '/var/www/' + s['domain']:
            raise ValueError('Неожиданные пути в данных установки.')
        print('Панель и сохранённые параметры проверены. Этап продолжения: ' + stage)
    elif cmd == 'report':
        s = read(args[0])
        print(f"Панель 3x-ui: {s['panel_url']}\nЛогин: {s['username']}\nПароль: {s['password']}\n"
              f"Режим: {s['profile']}\nВходящий IP: {s['inbound_ip']}\nВыходящий IP: {s['outbound_ip']}\n"
              f"Подписка: {s['subscription_url']}\nVLESS: {s['vless_link']}")
    else:
        raise ValueError('Неизвестная команда: ' + cmd)


if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        color = '\033[1;31m' if sys.stderr.isatty() and 'NO_COLOR' not in os.environ else ''
        reset = '\033[0m' if color else ''
        print(color + 'ОШИБКА: ' + str(exc) + reset, file=sys.stderr)
        sys.exit(1)
PY_CORE
}

archive_preinstall_attempt() {
  local directory="${1:-/root/vless-wiki}" entry backup
  [[ -d "$directory" ]] || return 0
  # Only an attempt that never reached the upstream installer can restart automatically.
  [[ -f "$directory/state.json" ]] || die "Неизвестные данные в $directory. Автоматический перезапуск остановлен."
  for entry in "$directory"/* "$directory"/.[!.]* "$directory"/..?*; do
    [[ -e "$entry" || -L "$entry" ]] || continue
    case "${entry##*/}" in
      state.json|nginx-before|ufw-before) ;;
      *) die "Найдены данные более позднего этапа: $entry. Проверь прошлую установку перед повторным запуском." ;;
    esac
  done
  backup=$(mktemp -d "${directory}-before-retry.XXXXXXXX")
  mv "$directory" "$backup/attempt"
  paint "$C_YELLOW" "Предыдущий запуск остановился до установки 3x-ui. Его данные сохранены: $backup/attempt"
}

firewall() {
  # Preserve the actual SSH session port, sshd config and socket-activation ports.
  local ports p
  ports="$( { (sshd -T 2>/dev/null || true) | awk '$1=="port" {print $2}';
     printf '%s\n' "${SSH_CONNECTION:-}" | awk 'NF==4 {print $4}';
     systemctl show ssh.socket -p Listen --value 2>/dev/null | sed -nE 's/.*:([0-9]+) .*/\1/p'; } | sort -un)"
  ports="${ports:-22}"
  for p in $ports; do
    [[ "$p" =~ ^[0-9]+$ ]] || continue
    ufw prepend allow "$p/tcp" >/dev/null
  done
  ufw default deny incoming >/dev/null
  ufw default allow outgoing >/dev/null
  ufw allow to "$INBOUND_IP" port 80 proto tcp >/dev/null
  ufw allow to "$INBOUND_IP" port 443 proto tcp >/dev/null
  ufw --force enable >/dev/null
}

install_scanner_block() {
  # Public scanner lists, AS61280 prefixes and additional scanner CIDRs.
  cat > /usr/local/sbin/vless-scanners-update <<'SCANNERS'
#!/usr/bin/env bash
set -Eeuo pipefail
umask 077
exec 9>/run/vless-scanners.lock
flock -n 9 || exit 0
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
sources=(
 https://raw.githubusercontent.com/shadow-netlab/traffic-guard-lists/refs/heads/main/public/antiscanner.list
 https://raw.githubusercontent.com/tread-lightly/CyberOK_Skipa_ips/refs/heads/main/lists/skipa_cidr.txt
)
: > "$work/raw"
for url in "${sources[@]}"; do
  if curl -fsSL --retry 2 --connect-timeout 10 --max-time 60 "$url" -o "$work/source"; then
    cat "$work/source" >> "$work/raw"; printf '\n' >> "$work/raw"
  else
    printf 'Не удалось скачать %s\n' "$url" >&2
  fi
 done
if curl -fsSL --connect-timeout 10 --max-time 60 'https://stat.ripe.net/data/announced-prefixes/data.json?resource=AS61280' -o "$work/asn.json"; then
  python3 - "$work/asn.json" >> "$work/raw" <<'PY_ASN'
import json,sys
for entry in json.load(open(sys.argv[1])).get('data',{}).get('prefixes',[]):
    print(entry['prefix'])
PY_ASN
fi
printf '\n85.142.100.0/24\n46.161.48.0/22\n95.215.0.0/24\n45.91.64.0/24\n' >> "$work/raw"
# Normalize CIDRs; allowlist /32 and IPv6 exceptions precede blocklist rules.
python3 - "$work/raw" "$work" <<'PY_LIST'
import ipaddress, pathlib, sys
raw, directory = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2])
nets = set()
for line in raw.read_text().splitlines():
    value = line.split('#')[0].strip()
    if not value: continue
    try:
        n = ipaddress.ip_network(value, strict=False)
        if n.prefixlen == 0: raise ValueError('Отказ: список содержит маршрут по умолчанию')
        nets.add(n)
    except ValueError:
        if value in ('0.0.0.0/0', '::/0'): raise
if len(nets) < 50:
    raise SystemExit('Меньше 50 корректных подсетей; предыдущие списки сохранены.')
for version in (4,6):
    rows = sorted((n for n in nets if n.version == version), key=lambda n: (int(n.network_address), n.prefixlen))
    (directory / str(version)).write_text(''.join(str(n)+'\n' for n in rows))
print(f'Подсетей сканеров: {len(nets)}')
PY_LIST
for v in 4 6; do
  family=inet; [[ $v == 4 ]] || family=inet6
  ipset create "vless_scan${v}" hash:net family "$family" maxelem 131072 -exist
  ipset destroy "vless_new${v}" 2>/dev/null || true
  ipset create "vless_new${v}" hash:net family "$family" maxelem 131072
  while IFS= read -r cidr; do printf 'add vless_new%s %s\n' "$v" "$cidr"; done < "$work/$v" > "$work/restore$v"
  ipset restore -exist < "$work/restore$v"
done
# Only swap after both candidates have been completely validated and loaded.
for v in 4 6; do ipset swap "vless_new${v}" "vless_scan${v}"; ipset destroy "vless_new${v}"; done
{ ipset save vless_scan4; ipset save vless_scan6; } > /etc/vless-scanners.ipset.tmp
mv /etc/vless-scanners.ipset.tmp /etc/vless-scanners.ipset
SCANNERS
  chmod 700 /usr/local/sbin/vless-scanners-update
  # Restore sets even before the first successful download, so ufw always reloads.
  cat > /etc/systemd/system/vless-scanners-restore.service <<'UNIT'
[Unit]
Description=Restore scanner blocklists before ufw
DefaultDependencies=no
After=local-fs.target
Before=ufw.service network-pre.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/sh -ec 'ipset create vless_scan4 hash:net family inet maxelem 131072 -exist; ipset create vless_scan6 hash:net family inet6 maxelem 131072 -exist; if [ -s /etc/vless-scanners.ipset ]; then ipset restore -exist -f /etc/vless-scanners.ipset; fi'
[Install]
WantedBy=ufw.service
UNIT
  cat > /etc/systemd/system/vless-scanners-update.service <<'UNIT'
[Unit]
Description=Download scanner blocklists
Wants=network-online.target
After=network-online.target vless-scanners-restore.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/vless-scanners-update
UNIT
  cat > /etc/systemd/system/vless-scanners-update.timer <<'UNIT'
[Unit]
Description=Daily scanner blocklist update
[Timer]
OnCalendar=*-*-* 05:00:00
RandomizedDelaySec=1h
Persistent=true
[Install]
WantedBy=timers.target
UNIT
  chmod 644 /etc/systemd/system/vless-scanners-{restore.service,update.service,update.timer}
  systemctl daemon-reload
  systemctl enable --now vless-scanners-restore.service
  # Put allowlist and drops before ufw user rules, after established connections.
  python3 - <<'PY_UFW'
import ipaddress, os
from pathlib import Path
allow = set()
connection = os.environ.get('SSH_CONNECTION','').split()
if connection:
    try: allow.add(ipaddress.ip_network(connection[0], strict=False))
    except ValueError: pass
p = Path('/etc/vless-scanners-allow.txt')
if p.exists():
    for row in p.read_text().splitlines():
        row = row.split('#')[0].strip()
        if row: allow.add(ipaddress.ip_network(row,strict=False))
p.write_text('# Доверенные адреса, исключённые из блокировки при установке.\n' + ''.join(str(n)+'\n' for n in sorted(allow,key=str)))
for v, filename, chain in ((4,'/etc/ufw/before.rules','ufw-before-input'), (6,'/etc/ufw/before6.rules','ufw6-before-input')):
    path = Path(filename); text = path.read_text()
    anchor = f'-A {chain} -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT'
    if anchor not in text: raise SystemExit('Не найдено место для правил в ' + filename)
    exceptions = ''.join(f'-A {chain} -s {n} -j ACCEPT\n' for n in sorted(allow,key=str) if n.version==v)
    rules = exceptions + f'-A {chain} -m set --match-set vless_scan{v} src -j DROP\n'
    import re
    text = re.sub(r'(?ms)\n# VLESS Wiki: trusted peers and scanners\n.*?^# END VLESS Wiki scanners\n', '', text)
    path.write_text(text.replace(anchor, anchor + '\n# VLESS Wiki: trusted peers and scanners\n' + rules + '# END VLESS Wiki scanners\n',1))
PY_UFW
  ufw reload
  systemctl enable --now vless-scanners-update.timer
  # Mandatory first download: fail visibly instead of claiming protection with empty sets.
  /usr/local/sbin/vless-scanners-update
}

ensure_acme() {
  local acme_home="${1:-/root/.acme.sh}" log="${2:-/root/vless-wiki/acme-install.log}"
  local acme="$acme_home/acme.sh"
  if [[ ! -x "$acme" ]]; then
    # Download the real CLI, not the bootstrap wrapper that can mask installation errors.
    fetch https://raw.githubusercontent.com/acmesh-official/acme.sh/master/acme.sh "$WORK/acme-install.sh"
    if ! sh "$WORK/acme-install.sh" --install-online --home "$acme_home" \
        --accountemail "admin@$DOMAIN" > "$log" 2>&1; then
      tail -n 30 "$log" >&2
      die "Не удалось установить acme.sh. Лог: $log"
    fi
  fi
  if [[ ! -x "$acme" ]]; then
    [[ ! -f "$log" ]] || tail -n 30 "$log" >&2
    die "Установщик acme.sh завершился, но файл $acme не создан. Лог: $log"
  fi
  "$acme" --version >> "$log" 2>&1 || die "acme.sh не запускается. Лог: $log"
}

resume_install() {
  local requested_domain="${DOMAIN:-}"
  STATE=/root/vless-wiki/state.json
  [[ -f "$STATE" && -x /usr/local/x-ui/x-ui && -f /etc/x-ui/x-ui.db ]] \
    || die 'Для --resume нужны сохранённые параметры и установленная этим скриптом панель 3x-ui.'
  [[ -f /etc/x-ui/install-result.env ]] || die 'Не найдены доступы установленной панели.'
  set -a
  . /etc/x-ui/install-result.env
  set +a
  # Refuse to re-provision a panel that already has inbounds or mismatching credentials.
  core resume-check "$STATE"
  DOMAIN=$(core get "$STATE" domain)
  [[ -z "$requested_domain" ]] || DOMAIN=$(core domain "$requested_domain")
  INBOUND_IP=$(core get "$STATE" inbound_ip)
  OUTBOUND_IP=$(core get "$STATE" outbound_ip)
  XRAY_BIN="/usr/local/x-ui/bin/xray-linux-$XARCH"
  [[ -x "$XRAY_BIN" ]] || die "Не найден $XRAY_BIN."
  WORK=$(mktemp -d /tmp/vless-install.XXXXXXXX)
  trap 'rm -rf "${WORK:-}"' EXIT
  trap 'report_failure "$LINENO"' ERR
  # Re-check DNS and local IPv4 before using saved networking parameters.
  ip -j addr show > "$WORK/addresses.json"
  fetch_dns A "$WORK/dns-a.json"
  fetch_dns AAAA "$WORK/dns-aaaa.json"
  core inventory "$WORK/addresses.json" "$WORK/dns-a.json" "$WORK/dns-aaaa.json" > "$WORK/plan.json"
  core change-domain "$STATE" "$DOMAIN" "$WORK/plan.json"
  CERT_DIR=$(core get "$STATE" cert_dir)
  SITE_DIR=$(core get "$STATE" site_dir)
  core set-binary "$STATE" "$XRAY_BIN"
  if [[ "$(core resume-stage "$STATE")" == nginx ]]; then
    paint "$C_YELLOW" 'Продолжаю с настройки nginx. Сертификат, клиент и ключи VPN сохраняются.'
    STEP=7
    finish_nginx
  else
    paint "$C_YELLOW" 'Продолжаю с выпуска сертификата. Существующие доступы панели сохраняются.'
    STEP=5
    finish_install
  fi
}

acme_http_preflight() {
  local root="${1:-/var/www/acme}" log="${2:-/root/vless-wiki/acme-http.log}"
  local token file url code attempt body="$WORK/acme-http-body"
  install -d -m 755 "$root" "$root/.well-known" "$root/.well-known/acme-challenge"
  token="vless-check-$(openssl rand -hex 16)"
  file="$root/.well-known/acme-challenge/$token"
  url="http://$DOMAIN/.well-known/acme-challenge/$token"
  printf '%s' "$token" > "$file"
  chmod 644 "$file"
  printf 'HTTP-01 preflight: %s -> %s:80\n' "$url" "$INBOUND_IP" > "$log"
  # Also wait for nginx's asynchronous reload to activate the new configuration.
  for attempt in 1 2 3 4 5; do
    code=$(curl -4 -sS --noproxy '*' --connect-timeout 5 --max-time 10 \
      --resolve "$DOMAIN:80:$INBOUND_IP" -o "$body" -w '%{http_code}' "$url" 2>> "$log") || code=transport-error
    printf 'Attempt %s: HTTP %s\n' "$attempt" "$code" >> "$log"
    if [[ "$code" == 200 ]] && cmp -s "$file" "$body"; then
      rm -f "$file" "$body"
      paint "$C_GREEN" 'HTTP-01: nginx отдаёт проверочный файл, путь и содержимое проверены.'
      return 0
    fi
    [[ $attempt == 5 ]] || sleep 1
  done
  ls -ld /var/www "$root" "$root/.well-known" "$root/.well-known/acme-challenge" "$file" >> "$log" 2>&1 || true
  if [[ -f "$body" ]]; then head -c 512 "$body" >> "$log"; printf '\n' >> "$log"; fi
  if [[ -f /var/log/nginx/error.log ]]; then tail -n 10 /var/log/nginx/error.log >> "$log"; fi
  rm -f "$file" "$body"
  tail -n 25 "$log" >&2
  die "nginx не отдаёт проверочный файл (HTTP $code). Запрос в Let's Encrypt не отправлен. Диагностика: $log"
}

activate_nginx() {
  nginx -t
  systemctl enable nginx
  # Replacing the distro wildcard :80 listener with a specific IPv4 requires
  # closing the old socket. A successful reload command does not prove bind succeeded.
  if ! systemctl restart nginx; then
    ss -ltnp '( sport = :80 or sport = :443 )' >&2 || true
    journalctl -u nginx -n 20 --no-pager >&2 || true
    die 'nginx не запустился. Проверь занятые порты и журнал. Последующие этапы остановлены.'
  fi
  systemctl is-active --quiet nginx || die 'nginx не активен после перезапуска. Последующие этапы остановлены.'
}

finish_install() {
  step 'Выпуск сертификата Let’s Encrypt'
  mkdir -p "$SITE_DIR" /var/www/acme "$CERT_DIR"
  chmod 755 "$SITE_DIR" /var/www/acme
  rm -f /etc/nginx/sites-enabled/default
  core nginx "$STATE" bootstrap > /etc/nginx/sites-available/vless-wiki
  chmod 644 /etc/nginx/sites-available/vless-wiki
  ln -sfn /etc/nginx/sites-available/vless-wiki /etc/nginx/sites-enabled/vless-wiki
  activate_nginx
  acme_http_preflight
  ensure_acme
  local acme=/root/.acme.sh/acme.sh rc=0
  "$acme" --set-default-ca --server letsencrypt >/dev/null
  "$acme" --issue -d "$DOMAIN" -w /var/www/acme --keylength ec-256 > /root/vless-wiki/acme.log 2>&1 || rc=$?
  [[ $rc == 0 || $rc == 2 ]] || die "$(core acme-error /root/vless-wiki/acme.log)"
  "$acme" --install-cert -d "$DOMAIN" --ecc --key-file "$CERT_DIR/privkey.pem" \
    --fullchain-file "$CERT_DIR/fullchain.pem" --reloadcmd 'systemctl reload nginx' >> /root/vless-wiki/acme.log 2>&1
  step 'Настройка XHTTP, Vision и выхода через выбранный IP'
  core provision "$STATE"
  finish_nginx

}

prepare_default_tls() {
  local compatibility
  compatibility=$(core nginx-compat "$STATE")
  if [[ "$compatibility" == legacy ]]; then
    paint "$C_YELLOW" 'nginx старше 1.19.4: использую совместимый TLS-блок с отдельным сертификатом localhost.'
    if [[ ! -s /root/vless-wiki/default-tls.crt || ! -s /root/vless-wiki/default-tls.key ]]; then
      openssl req -x509 -newkey rsa:2048 -sha256 -nodes -days 3650 -subj /CN=localhost \
        -keyout /root/vless-wiki/default-tls.key -out /root/vless-wiki/default-tls.crt \
        > /root/vless-wiki/default-tls.log 2>&1
      chmod 600 /root/vless-wiki/default-tls.key /root/vless-wiki/default-tls.crt
    fi
  fi
}

finish_nginx() {
  step 'Настройка nginx: сайт, панель и подписка'
  [[ -s "$CERT_DIR/fullchain.pem" && -s "$CERT_DIR/privkey.pem" ]] || die 'Не найдены ранее выпущенные сертификат и ключ.'
  paint "$C_BLUE" '3x-ui: настройка блокировки российских направлений'
  core block-ru "$STATE"
  prepare_default_tls
  # Ordinary browser requests receive the standard nginx 404 page.
  core nginx "$STATE" > /etc/nginx/sites-available/vless-wiki
  chmod 644 /etc/nginx/sites-available/vless-wiki
  activate_nginx
  # Save credentials and links before tests, so a failed test never loses access data.
  core report "$STATE" > /root/vless-wiki/access.txt
  SUBSCRIPTION_URL=$(core get "$STATE" subscription_url)
  qrencode -t PNG -s 8 -o /root/vless-wiki/subscription-qr.png "$SUBSCRIPTION_URL"
  step 'Блокировка подсетей сканеров и РКН'
  install_scanner_block
  step 'Проверка сайта, панели, подписки и готовой VLESS-ссылки'
  local failed=0
  local site_status
  site_status=$(curl -4 -sS --max-time 20 -o /dev/null -w '%{http_code}' "https://$DOMAIN/" || true)
  if [[ "$site_status" != 404 ]]; then
    paint "$C_RED" "Заглушка nginx: ожидался HTTP 404, получен ${site_status:-нет ответа}."
    failed=1
  fi
  curl -4 -fsS --max-time 20 "$(core get "$STATE" panel_url)" -o /dev/null || failed=1
  curl -4 -fsS --max-time 20 "$(core get "$STATE" subscription_url)" -o "$WORK/subscription.txt" || failed=1
  if ! core check-subscription "$STATE" "$WORK/subscription.txt"; then failed=1; fi
  if ! core selftest "$STATE" /root/vless-wiki; then failed=1; fi
  printf '\n'
  if [[ $failed == 0 ]]; then
    paint "$C_GREEN" 'Готово. Проверки пройдены.'
    printf '\n'
  else
    paint "$C_RED" 'Установка завершена, но проверки НЕ пройдены. Проверь логи перед использованием.'
    printf '\n'
  fi
  while IFS= read -r line; do paint "$C_BOLD" "$line"; done < /root/vless-wiki/access.txt
  printf '\n'; paint "$C_BLUE" 'QR-код подписки:'
  qrencode -t ANSIUTF8 -m 1 "$SUBSCRIPTION_URL"
  printf '\nДоступы: /root/vless-wiki/access.txt\nQR PNG: /root/vless-wiki/subscription-qr.png\nДля XHTTP + Vision нужен клиент с поддержкой VLESS Encryption.\n'
  [[ ! -f /var/run/reboot-required ]] || paint "$C_YELLOW" 'После обновления системы требуется перезагрузка.'
  return "$failed"
}

main() {
  local DOMAIN='' REQUESTED_MODE='' PROFILE='' REQUEST_RESUME=0 p
  STEP=0
  init_colors
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -d|--domain) [[ $# -ge 2 ]] || die 'После --domain нужен домен.'; DOMAIN=$2; shift 2 ;;
      --mode) [[ $# -ge 2 ]] || die 'После --mode нужен tls или reality.'; REQUESTED_MODE=$2; shift 2 ;;
      --resume) REQUEST_RESUME=1; shift ;;
      -h|--help) usage; return 0 ;;
      *) die "Неизвестный параметр: $1" ;;
    esac
  done
  [[ -z "$REQUESTED_MODE" || "$REQUESTED_MODE" == tls || "$REQUESTED_MODE" == reality ]] || die 'Режим: tls или reality.'
  [[ $EUID -eq 0 ]] || die 'Запусти от root: sudo bash install.sh --domain vpn.example.com'
  [[ -f /etc/os-release ]] || die 'Не найдена информация о системе.'
  . /etc/os-release
  case "$ID:$VERSION_ID" in ubuntu:22.04|ubuntu:24.04|debian:12|debian:13) ;; *) die 'Нужен Ubuntu 22.04/24.04 или Debian 12/13.' ;; esac
  case "$(uname -m)" in x86_64|amd64) XARCH=amd64 ;; aarch64|arm64) XARCH=arm64 ;; *) die 'Поддерживаются amd64 и arm64.' ;; esac
  command -v systemctl >/dev/null || die 'Нужна система с systemd.'
  if [[ $REQUEST_RESUME == 1 ]]; then
    [[ -z "$REQUESTED_MODE" ]] || die '--resume сохраняет ранее выбранный режим. Не передавай --mode.'
    resume_install
    return
  fi
  [[ ! -e /usr/local/x-ui && ! -e /etc/x-ui/x-ui.db && ! -e /usr/local/etc/xray/config.json ]] || die 'Обнаружен Xray или 3x-ui. Нужен чистый сервер; существующая установка не изменена.'
  archive_preinstall_attempt
  [[ -n "$DOMAIN" ]] || ask 'Домен (например vpn.example.com): ' DOMAIN
  # No system mutation before platform and existing-installation checks above.
  export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a
  local apt_options=(-y -q -o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold)
  step 'Обновление системы'
  apt-get update -q
  apt-get upgrade "${apt_options[@]}"
  apt-get install "${apt_options[@]}" python3 curl ca-certificates iproute2 openssl nginx ufw ipset qrencode cron socat tar util-linux
  DOMAIN=$(core domain "$DOMAIN")
  WORK=$(mktemp -d /tmp/vless-install.XXXXXXXX)
  trap 'rm -rf "${WORK:-}"' EXIT
  trap 'report_failure "$LINENO"' ERR
  step 'Поиск IP и проверка DNS'
  ip -j addr show > "$WORK/addresses.json"
  fetch_dns A "$WORK/dns-a.json"
  fetch_dns AAAA "$WORK/dns-aaaa.json"
  core inventory "$WORK/addresses.json" "$WORK/dns-a.json" "$WORK/dns-aaaa.json" > "$WORK/plan.json"
  printf 'Все адреса интерфейсов:\n'; core get "$WORK/plan.json" all_ips
  local count
  count=$(core get "$WORK/plan.json" public_ipv4 | wc -l | tr -d ' ')
  show_modes "$count"
  if [[ -n "$REQUESTED_MODE" ]]; then
    PROFILE=$(core select "$WORK/plan.json" "$REQUESTED_MODE")
  else
    local choice
    while true; do
      ask 'Выбери доступный вариант: ' choice
      [[ "$choice" != 0 ]] || return 0
      if PROFILE=$(core select "$WORK/plan.json" "$choice"); then break; fi
    done
  fi
  INBOUND_IP=$(core get "$WORK/plan.json" inbound_ip)
  OUTBOUND_IP=$(core profile-outbound "$WORK/plan.json" "$PROFILE")
  paint "$C_GREEN" "Выбран режим: $PROFILE"
  paint "$C_BLUE" "Входящий IPv4: $INBOUND_IP"
  paint "$C_BLUE" "Выходящий IPv4: $OUTBOUND_IP"
  step 'Проверка выхода через выбранный IP'
  local actual='' endpoint
  for endpoint in https://api.ipify.org https://ifconfig.me/ip; do
    actual=$(curl -4 -fsS --interface "$OUTBOUND_IP" --connect-timeout 10 --max-time 20 "$endpoint" || true)
    [[ "$actual" != "$OUTBOUND_IP" ]] || break
  done
  [[ "$actual" == "$OUTBOUND_IP" ]] || die "Выход с $OUTBOUND_IP не работает или у хостинга NAT. Получен адрес: ${actual:-нет}."
  # A fresh distro nginx may already own 80. Only its stock default site is replaced.
  for p in /etc/nginx/sites-enabled/* /etc/nginx/conf.d/*.conf; do
    [[ -e "$p" ]] || continue
    [[ "$p" == /etc/nginx/sites-enabled/default ]] || die "Найден сторонний nginx-конфиг $p. Нужен чистый сервер."
  done
  if ss -ltnH '( sport = :443 )' | grep -q .; then die 'Порт 443 уже занят.'; fi
  if ss -ltnH '( sport = :80 )' | grep -q .; then
    ss -ltnpH '( sport = :80 )' | grep -q nginx || die 'Порт 80 занят другим сервисом.'
  fi
  install -d -m 700 /root/vless-wiki
  STATE=/root/vless-wiki/state.json
  core init "$WORK/plan.json" "$STATE" "$DOMAIN" "$PROFILE"
  PANEL_PORT=$(core get "$STATE" panel_port)
  WEB_PATH=$(core get "$STATE" web_path)
  XUI_USER=$(core get "$STATE" username)
  XUI_PASS=$(core get "$STATE" password)
  CERT_DIR=$(core get "$STATE" cert_dir)
  SITE_DIR=$(core get "$STATE" site_dir)
  step 'Фаервол и сохранение доступа SSH'
  cp -a /etc/nginx /root/vless-wiki/nginx-before
  cp -a /etc/ufw /root/vless-wiki/ufw-before
  firewall
  # Block the temporary public panel listener before the upstream installer starts it.
  ufw prepend deny "$PANEL_PORT/tcp" >/dev/null
  step 'Установка 3x-ui'
  fetch https://raw.githubusercontent.com/MHSanaei/3x-ui/main/install.sh "$WORK/3xui-install.sh"
  XUI_NONINTERACTIVE=1 XUI_DB_TYPE=sqlite XUI_SSL_MODE=none XUI_PANEL_PORT="$PANEL_PORT" \
    XUI_SERVER_IP="$INBOUND_IP" XUI_WEB_BASE_PATH="$WEB_PATH" XUI_USERNAME="$XUI_USER" XUI_PASSWORD="$XUI_PASS" \
    bash "$WORK/3xui-install.sh" > /root/vless-wiki/3xui-install.log 2>&1 \
    || die '3x-ui не установился. Лог: /root/vless-wiki/3xui-install.log'
  [[ -x /usr/local/x-ui/x-ui && -f /etc/x-ui/x-ui.db ]] || die 'Не найдены бинарник или SQLite-база 3x-ui.'
  /usr/local/x-ui/x-ui setting -listenIP 127.0.0.1 >/dev/null
  systemctl restart x-ui
  # Official installer persists shell-escaped values in a root-owned mode-600 file.
  [[ -f /etc/x-ui/install-result.env ]] || die 'Нет файла результатов установки 3x-ui.'
  set -a
  . /etc/x-ui/install-result.env
  set +a
  core wait "$STATE"
  XRAY_BIN="/usr/local/x-ui/bin/xray-linux-$XARCH"
  [[ -x "$XRAY_BIN" ]] || die "Не найден $XRAY_BIN."
  core set-binary "$STATE" "$XRAY_BIN"
  finish_install

}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  main "$@"
fi
