#!/usr/bin/env python3
"""DGX Spark bootstrap; private assets use encrypted, hash-verified downloads."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import platform
import pwd
import re
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request

LOG = Path('/var/log/spark-bootstrap.log')
PRIVATE = Path('/etc/spark-bootstrap')
PROXY = 'http://127.0.0.1:17652'
SECRETS = []
CFG = {}
ASSETS = None
TS = None
USER = None
PROXY_READY = False
PROXY_PREPARED = False


class Failure(Exception):
    def __init__(self, code, message, action):
        self.code, self.message, self.action = code, message, action


def clean(text):
    for secret in SECRETS:
        if len(str(secret)) >= 4:
            text = text.replace(str(secret), '[已隐藏]')
    text = re.sub(r'tskey-[A-Za-z0-9_-]+', '[已隐藏]', text)
    return re.sub(r'https://login\.tailscale\.com/[^\s]+', '[授权链接已隐藏]', text)


def note(message):
    print(message, flush=True)
    if os.geteuid() == 0:
        with LOG.open('a') as stream:
            stream.write(time.strftime('%Y-%m-%d %H:%M:%S ') + clean(message) + '\n')
        LOG.chmod(0o600)


def run(argv, timeout=30, check=True, env=None, log_output=True):
    options = dict(os.environ)
    options.update({'LC_ALL': 'C', 'DEBIAN_FRONTEND': 'noninteractive'})
    if env:
        options.update(env)
    process = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                               text=True, env=options, start_new_session=True)
    started = time.monotonic()
    executable = Path(argv[0]).name
    activity = ('下载并安装 SSH 组件' if executable == 'apt-get' and 'install' in argv
                else '刷新软件包索引' if executable == 'apt-get'
                else '连接并授权 Tailscale' if executable == 'tailscale' and 'up' in argv
                else '启动或检查系统服务')
    try:
        while True:
            remaining = timeout - (time.monotonic() - started)
            if remaining <= 0:
                raise subprocess.TimeoutExpired(argv, timeout)
            try:
                output, _ = process.communicate(timeout=min(10, remaining))
                break
            except subprocess.TimeoutExpired:
                if time.monotonic() - started >= timeout:
                    raise
                note('  仍在' + activity + '，已进行 ' + str(int(time.monotonic() - started)) +
                     ' 秒（本次最多等待 ' + str(timeout) + ' 秒），请保持窗口打开。')
    except subprocess.TimeoutExpired:
        os.killpg(process.pid, signal.SIGTERM)
        try:
            output, _ = process.communicate(timeout=8)
        except subprocess.TimeoutExpired:
            os.killpg(process.pid, signal.SIGKILL)
            output, _ = process.communicate()
        if check:
            raise Failure('E_TIMEOUT', '当前步骤超过等待时间。', '保持机器联网，稍后重跑同一条命令；若仍失败，发送日志末尾。')
        return 124, output or ''
    if output and log_output and os.geteuid() == 0:
        with LOG.open('a') as stream:
            stream.write(clean(output[-6000:]) + '\n')
    if check and process.returncode:
        code = 'E_LOCK' if re.search(r'Could not get lock|Unable to acquire.*lock', output) else 'E_COMMAND'
        raise Failure(code, '系统命令未成功完成。', '请把 /var/log/spark-bootstrap.log 最后 40 行发给远程操作人员。')
    return process.returncode, output


def write(path, text, mode=0o600):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
        temporary = Path(stream.name)
        stream.write(text.encode())
        os.fchmod(stream.fileno(), mode)
    os.replace(temporary, path)


def asset(name):
    matches = [p for p in ASSETS.rglob(name) if p.is_file() and not p.is_symlink()]
    if len(matches) != 1:
        raise Failure('E_ASSET', '安装包缺少或重复包含必要文件：' + name, '重新执行下载命令，勿混用不同安装包。')
    return matches[0]


def binary(name, destination):
    source = asset(name)
    Path(destination).parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=Path(destination).parent, delete=False) as stream:
        temporary = Path(stream.name)
    try:
        shutil.copyfile(source, temporary)
        os.chmod(temporary, 0o755)
        os.replace(temporary, destination)
    finally:
        temporary.unlink(missing_ok=True)


def state():
    if not TS:
        return {}
    code, output = run([TS, 'status', '--json'], check=False)
    try:
        return json.loads(output)
    except (ValueError, TypeError):
        return {}


def probe(proxy=False):
    opener = urllib.request.build_opener(urllib.request.ProxyHandler({'http': PROXY, 'https': PROXY} if proxy else {}))
    last = ''
    for endpoint in ('https://controlplane.tailscale.com/', 'https://login.tailscale.com/'):
        try:
            with opener.open(endpoint, timeout=8) as response:
                if response.status >= 500:
                    raise OSError('HTTP server unavailable')
        except urllib.error.HTTPError as error:
            if error.code < 500:
                continue
            last = str(error)
        except Exception as error:
            last = str(error)
        if last:
            return False, last
    return True, ''


def network_code(error):
    lowered = error.lower()
    if 'name or service' in lowered or 'name resolution' in lowered or 'no such host' in lowered:
        return 'E_DNS', '域名解析失败，请确认网络和 DNS 可用。'
    if 'certificate' in lowered or 'tls' in lowered or 'ssl' in lowered:
        return 'E_TLS', 'HTTPS 验证失败，请检查机器日期、时间及网络认证页面。'
    if 'timed out' in lowered or 'timeout' in lowered:
        return 'E_TIMEOUT', '连接超时，请确认网线已接好并可正常上网。'
    return 'E_CONTROL', '暂时无法连接 Tailscale 控制服务，请检查网络。'


def enable_proxy():
    global PROXY_READY
    if PROXY_READY:
        return
    if not PROXY_PREPARED:
        prepare_proxy()
    note('正在启用常驻代理，仅监听本机 127.0.0.1:17652，开机自动启动。')
    was_active, _ = run(['systemctl', 'is-active', '--quiet', 'spark-bootstrap-proxy.service'], check=False)
    rc, _ = run(['systemctl', 'enable', '--now', 'spark-bootstrap-proxy.service'], check=False)
    if not rc and was_active == 0:
        rc, _ = run(['systemctl', 'restart', 'spark-bootstrap-proxy.service'], check=False)
    active, _ = run(['systemctl', 'is-active', '--quiet', 'spark-bootstrap-proxy.service'], check=False)
    enabled, _ = run(['systemctl', 'is-enabled', '--quiet', 'spark-bootstrap-proxy.service'], check=False)
    if rc or active or enabled:
        raise Failure('E_PROXY_SERVICE', '本地代理未能正常自启或运行。', 'SSH 连通后检查 systemctl status spark-bootstrap-proxy；不要修改系统路由。')
    for _ in range(3):
        okay, error = probe(True)
        if okay:
            PROXY_READY = True
            note('常驻代理已运行、已设开机自启，HTTPS 连接检查通过。')
            return
        time.sleep(2)
    code, action = network_code(error)
    raise Failure('E_PROXY/' + code, '代理服务已运行，但未能通过 HTTPS 连接检查。', action + ' SSH 连通后执行 spark-proxy --check 复查。')


def proxy_tailscale():
    enable_proxy()
    write('/etc/systemd/system/tailscaled.service.d/spark-bootstrap-proxy.conf',
          '[Service]\nEnvironment="HTTP_PROXY=' + PROXY + '" "HTTPS_PROXY=' + PROXY + '" "NO_PROXY=localhost,127.0.0.1,100.64.0.0/10"\n')
    run(['systemctl', 'daemon-reload'])
    run(['systemctl', 'restart', 'tailscaled'])


def prepare_proxy():
    global PROXY_PREPARED
    config = CFG.get('proxy_config')
    if not isinstance(config, dict):
        raise Failure('E_PROXY_CONFIG', '备用代理配置缺失。', '请让远程操作人员重新生成安装包。')
    inbounds = config.get('inbounds', [])
    if len(inbounds) != 1 or inbounds[0].get('type') not in ('mixed', 'http') or inbounds[0].get('listen') != '127.0.0.1' or inbounds[0].get('listen_port') != 17652:
        raise Failure('E_PROXY_CONFIG', '代理入口配置不符合本机限定要求。', '请重新生成仅监听 127.0.0.1:17652、无 TUN 的配置。')
    binary('sing-box', '/opt/spark-bootstrap/bin/sing-box')
    PRIVATE.mkdir(parents=True, exist_ok=True)
    PRIVATE.chmod(0o700)
    write(PRIVATE / 'proxy.json', json.dumps(config))
    rc, _ = run(['/opt/spark-bootstrap/bin/sing-box', 'check', '-c', str(PRIVATE / 'proxy.json')], check=False, log_output=False)
    if rc:
        raise Failure('E_PROXY_CONFIG', '备用代理程序或配置未通过检查。', '请发送日志末尾；需要负责人检查软件架构和代理配置，现场无需改路由。')
    write('/etc/systemd/system/spark-bootstrap-proxy.service', '[Unit]\nDescription=Spark bootstrap local proxy\nAfter=network-online.target\nWants=network-online.target\n[Service]\nExecStart=/opt/spark-bootstrap/bin/sing-box run -c /etc/spark-bootstrap/proxy.json\nRestart=on-failure\nRestartSec=5\n[Install]\nWantedBy=multi-user.target\n', 0o644)
    write('/usr/local/bin/spark-proxy', '#!/bin/sh\nset -eu\nexport http_proxy=http://127.0.0.1:17652\nexport https_proxy="$http_proxy" all_proxy="$http_proxy"\nexport HTTP_PROXY="$http_proxy" HTTPS_PROXY="$http_proxy"\nexport NO_PROXY=localhost,127.0.0.1,::1,100.64.0.0/10\nexport no_proxy="$NO_PROXY"\nif [ "$#" -eq 0 ]; then\n    printf \'%s\\n\' \'本机代理：http://127.0.0.1:17652\' \'用法：spark-proxy curl URL\' \'      spark-proxy pip install 包名\' \'      sudo spark-proxy apt-get update\' \'检查：spark-proxy --check\' \'需要管理员权限时，把 sudo 放在 spark-proxy 前面。\'\n    exit 0\nfi\nif [ "$1" = sudo ]; then\n    printf \'%s\\n\' \'E_USAGE：sudo 会清除代理环境，请改用 sudo spark-proxy 后接命令。\' >&2\n    exit 2\nfi\nif [ "$1" = --check ]; then\n    if [ "$#" -ne 1 ]; then\n        printf \'%s\\n\' \'E_USAGE：--check 后面不需要其他参数。\' >&2\n        exit 2\n    fi\n    if ! command -v curl >/dev/null 2>&1; then\n        printf \'%s\\n\' \'E_PROXY_CHECK：未找到 curl，请先安装 curl。\' >&2\n        exit 3\n    fi\n    printf \'%s\\n\' \'正在通过本机代理检查 HTTPS 连接……\'\n    if curl --proxy "$https_proxy" --noproxy \'\' --fail --silent --show-error --location --connect-timeout 8 --max-time 25 -o /dev/null https://pkgs.tailscale.com/stable/; then\n        printf \'%s\\n\' \'代理 HTTPS 检查通过。\'\n        exit 0\n    else\n        result=$?\n        printf \'%s\\n\' \'E_PROXY_CHECK：代理 HTTPS 检查失败，请检查 systemctl status spark-bootstrap-proxy。\' >&2\n        exit "$result"\n    fi\nfi\nexec "$@"\n', 0o755)
    run(['systemctl', 'daemon-reload'])
    PROXY_PREPARED = True


def install_tailscale():
    global TS
    TS = shutil.which('tailscale')
    if not TS:
        binary('tailscale', '/usr/local/bin/tailscale')
        TS = '/usr/local/bin/tailscale'
    daemon = shutil.which('tailscaled') or next((p for p in ['/usr/sbin/tailscaled', '/usr/local/sbin/tailscaled'] if Path(p).exists()), None)
    if not daemon:
        binary('tailscaled', '/usr/local/sbin/tailscaled')
        daemon = '/usr/local/sbin/tailscaled'
    exists, _ = run(['systemctl', 'cat', 'tailscaled.service'], check=False)
    if exists:
        write('/etc/systemd/system/tailscaled.service', '[Unit]\nDescription=Tailscale node agent\nWants=network-online.target\nAfter=network-online.target\n[Service]\nExecStart=' + daemon + ' --state=/var/lib/tailscale/tailscaled.state --socket=/run/tailscale/tailscaled.sock --port=41641\nRuntimeDirectory=tailscale\nStateDirectory=tailscale\nRestart=on-failure\nRestartSec=5\n[Install]\nWantedBy=multi-user.target\n', 0o644)
        run(['systemctl', 'daemon-reload'])
    run(['systemctl', 'enable', '--now', 'tailscaled'])


def install_ssh(codename, architecture):
    if Path('/usr/sbin/sshd').exists():
        return
    note('正在安装 SSH 服务：依次尝试原软件源、国内镜像、备用代理。')
    base = ['apt-get', '-o', 'DPkg::Lock::Timeout=30', '-o', 'Acquire::Retries=1', '-o', 'Acquire::http::Timeout=15', '-o', 'Acquire::https::Timeout=15']
    with tempfile.TemporaryDirectory(prefix='spark-apt-') as directory:
        os.chmod(directory, 0o755)
        sources = Path(directory) / 'sources.list'
        repo = 'ubuntu-ports' if architecture == 'aarch64' else 'ubuntu'
        sources.write_text(''.join('deb [signed-by=/usr/share/keyrings/ubuntu-archive-keyring.gpg] https://mirrors.tuna.tsinghua.edu.cn/' + repo + '/ ' + codename + suffix + ' main universe\n' for suffix in ['', '-updates', '-security']))
        sources.chmod(0o644)
        mirror = ['-o', 'Dir::Etc::sourcelist=' + str(sources), '-o', 'Dir::Etc::sourceparts=-']
        last = ''
        for mode in range(3):
            options = [] if mode == 0 else mirror
            if mode == 2:
                enable_proxy()
                options = ['-o', 'Acquire::http::Proxy=' + PROXY, '-o', 'Acquire::https::Proxy=' + PROXY]
            rc, last = run(base + options + ['-o', 'APT::Update::Error-Mode=any', 'update'], 150, False)
            if rc == 0:
                rc, last = run(base + options + ['install', '-y', '--no-install-recommends', 'openssh-server'], 180, False)
                if rc == 0 and Path('/usr/sbin/sshd').exists():
                    return
            if re.search(r'Could not get lock|Unable to acquire.*lock', last):
                raise Failure('E_LOCK', '系统正在安装或更新其他软件。', '等待现场更新结束，再执行同一条命令；不要删除软件锁文件。')
    raise Failure('E_PACKAGE', '三个下载路径均未完成 SSH 安装。', '请发送日志末尾；已保留原软件源配置，可安全重跑。')


def configure_ssh():
    key = CFG.get('ssh_public_key', '').strip()
    if '\n' in key or not re.match(r'^(ssh-ed25519|ssh-rsa|ecdsa-sha2-\S+) [A-Za-z0-9+/=]+(?: .*)?$', key):
        raise Failure('E_SSH_KEY', '远程登录公钥格式错误。', '请让远程操作人员重新生成安装包。')
    directory = Path(USER.pw_dir) / '.ssh'
    target = directory / 'authorized_keys'
    if directory.is_symlink() or target.is_symlink():
        raise Failure('E_SSH_PATH', 'SSH 密钥路径是符号链接，已保留现状。', '请让管理员确认目标用户的 SSH 目录后重试。')
    directory.mkdir(mode=0o700, exist_ok=True)
    directory.chmod(0o700)
    os.chown(directory, USER.pw_uid, USER.pw_gid)
    content = target.read_text() if target.exists() else ''
    if key not in content.splitlines():
        write(target, content.rstrip('\n') + ('\n' if content else '') + key + '\n')
    target.chmod(0o600)
    os.chown(target, USER.pw_uid, USER.pw_gid)
    Path('/run/sshd').mkdir(exist_ok=True)
    rc, _ = run(['/usr/sbin/sshd', '-t'], check=False)
    if rc:
        raise Failure('E_SSH_CONFIG', '现有 SSH 配置检查未通过。', '请让管理员检查日志；安装器未修改密码或 root 登录设置。')
    run(['systemctl', 'enable', '--now', 'ssh'])
    if shutil.which('ufw'):
        _, status = run(['ufw', 'status'], check=False)
        if 'Status: active' in status:
            run(['ufw', 'allow', 'in', 'on', 'tailscale0', 'to', 'any', 'port', '22', 'proto', 'tcp'])


def login():
    identity = Path('/etc/machine-id').read_text().strip()[:6]
    args = [TS, 'up', '--hostname=dgx-spark-' + identity, '--accept-dns=false', '--timeout=45s']
    key = CFG.get('auth_key', '') if time.time() < CFG.get('expires_at', 0) else ''
    rc, output = 1, ''
    if key:
        with tempfile.TemporaryDirectory(prefix='spark-auth-', dir='/run') as directory:
            path = Path(directory) / 'authkey'
            write(path, key)
            for attempt in range(2):
                rc, output = run(args + ['--auth-key=file:' + str(path)], 55, False)
                if rc == 0 or re.search(r'invalid.*key|key.*(invalid|expired|used)|not authorized|401|403', output, re.I):
                    break
                if attempt == 0:
                    proxy_tailscale()
    if rc and state().get('BackendState') == 'NeedsMachineAuth':
        raise Failure('E_APPROVAL', '设备已经提交加入申请，正在等待管理员审批。', '请在 Tailscale 管理后台批准此设备，随后重跑同一条命令。')
    if rc:
        note('E_AUTH：自动授权未完成，现已切换为浏览器授权；已安装服务保持运行。')
        rc, output = run(args, 55, False)
        urls = re.findall(r'https://login\.tailscale\.com/[^\s]+', output)
        if not urls:
            code, action = network_code(output)
            raise Failure(code, '未能取得浏览器授权链接。', action + ' 请发送日志末尾。')
        print('请把下面的授权链接交给远程操作人员打开：\n' + urls[-1], flush=True)
        note('等待授权完成，最多 3 分钟；超时后服务仍会继续运行。')
        for _ in range(60):
            backend = state().get('BackendState')
            if backend == 'Running':
                return
            if backend == 'NeedsMachineAuth':
                raise Failure('E_APPROVAL', '登录已完成，设备还需要管理员审批。', '请在 Tailscale 管理后台批准此设备，再重跑命令。')
            time.sleep(3)
        raise Failure('E_AUTH_PENDING', '授权仍未完成，安装服务已保留。', '完成链接授权后重跑同一条命令即可继续检查。')


def verify():
    data = state()
    addresses = [x for x in (data.get('TailscaleIPs') or []) if x.startswith('100.')]
    rc, _ = run(['systemctl', 'is-active', '--quiet', 'ssh'], check=False)
    _, listeners = run(['ss', '-lnt'], check=False)
    key_ok = CFG['ssh_public_key'].strip() in (Path(USER.pw_dir) / '.ssh/authorized_keys').read_text().splitlines()
    if data.get('BackendState') != 'Running' or not addresses:
        raise Failure('E_CONTROL', 'Tailscale 尚未连接完成。', '保持网络连接，稍后重跑；如需审批，请在管理后台批准设备。')
    if rc or not re.search(r':22\s', listeners) or not key_ok:
        raise Failure('E_SSH', 'SSH 服务、22 端口或授权公钥检查未通过。', '请发送日志末尾，由远程操作人员检查现有 SSH 配置。')
    note('本机检查通过。远程操作人员可执行：ssh -i ~/.ssh/id_ed25519_spark ' + USER.pw_name + '@' + addresses[0])
    note('尚需从控制端实际登录，才能确认端到端远程访问成功。')
    active, _ = run(['systemctl', 'is-active', '--quiet', 'spark-bootstrap-proxy.service'], check=False)
    if active or not PROXY_READY:
        note('W_PROXY：远程登录准备已完成，代理仍需执行 spark-proxy --check 复查。')
    else:
        note('代理可用：spark-proxy curl URL；spark-proxy pip install 包名；sudo spark-proxy apt-get update。')


def main():
    global CFG, ASSETS, USER, TS
    parser = argparse.ArgumentParser()
    parser.add_argument('--assets-dir', required=True)
    parser.add_argument('--check-only', action='store_true')
    parser.add_argument('--skip-login', action='store_true')
    options = parser.parse_args()
    if os.geteuid() != 0:
        raise Failure('E_SUDO', '需要管理员权限才能安装服务。', '请通过 sudo 执行现场安装命令，并输入当前用户密码。')
    LOG.touch(mode=0o600, exist_ok=True)
    LOG.chmod(0o600)
    ASSETS = Path(options.assets_dir).resolve()
    CFG = json.loads((ASSETS / 'config.json').read_text())
    def secrets(value, key=''):
        if isinstance(value, dict):
            for k, v in value.items(): secrets(v, k)
        elif isinstance(value, list):
            for v in value: secrets(v, key)
        elif re.search(r'key|password|token|secret|uuid|username|account|credential|authorization', key, re.I):
            SECRETS.append(str(value))
    secrets(CFG)
    note('第 1/6 步：检查系统、空间和登录用户。')
    release = dict(line.split('=', 1) for line in Path('/etc/os-release').read_text().splitlines() if '=' in line)
    release = {k: v.strip('"') for k, v in release.items()}
    arch = platform.machine()
    if release.get('ID') != 'ubuntu' or int(release.get('VERSION_ID', '0').split('.')[0]) < 24 or arch not in ('aarch64', 'x86_64'):
        raise Failure('E_SYSTEM', '此安装器需要 Ubuntu 24.04 或更新版本、ARM64 或 x86_64。', '请确认机器运行原厂 DGX OS，并把系统版本发给远程操作人员。')
    if not Path('/run/systemd/system').is_dir():
        raise Failure('E_SYSTEMD', '未检测到正在运行的 systemd。', '请在 Spark 本机终端执行，不要在普通容器里执行。')
    if shutil.disk_usage('/').free < 400 * 1024 * 1024:
        raise Failure('E_DISK', '系统盘空闲空间不足 400 MB。', '请释放磁盘空间后重跑。')
    candidates = [p for p in pwd.getpwall() if 1000 <= p.pw_uid < 65534 and p.pw_shell not in ('/bin/false', '/usr/sbin/nologin', '/sbin/nologin') and Path(p.pw_dir).is_dir()]
    selected = [p for p in candidates if p.pw_name == os.environ.get('SUDO_USER')]
    if os.environ.get('SUDO_USER') not in (None, '', 'root') and not selected:
        raise Failure('E_USER', 'sudo 来源用户不符合普通登录用户要求。', '请用 Spark 的普通登录用户重新执行命令。')
    selected = selected or candidates
    if len(selected) != 1:
        raise Failure('E_USER', '无法唯一确定 SSH 登录用户。', '请以要远程登录的普通用户打开终端，通过 sudo 执行安装命令。')
    USER = selected[0]
    note('目标登录用户：' + USER.pw_name)
    if options.check_only:
        note('系统预检查通过，未安装或修改服务。')
        return
    with open('/run/spark-bootstrap.lock', 'w') as lock:
        try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError: raise Failure('E_LOCK', '另一份安装器正在运行。', '等待它结束后再重跑，不要并发粘贴安装命令。')
        TS = shutil.which('tailscale')
        previous = state()
        existing = previous.get('BackendState') in ('Running', 'NeedsMachineAuth') or ((previous.get('Self') or {}).get('UserID', 0) and previous.get('BackendState') == 'Stopped')
        note('第 2/6 步：准备网络连接。' + ('检测到已有登录，保留 Tailscale 原配置。' if existing else ''))
        prepare_proxy()
        direct, _ = probe()
        try:
            enable_proxy()
        except Failure as error:
            if not direct:
                raise
            note('W_PROXY：' + error.message + ' 当前直连可用，继续配置 SSH。\n后续处理：' + error.action)
        if not existing:
            install_tailscale()
            if not direct: proxy_tailscale()
        note('第 3/6 步：准备普通 SSH 服务。')
        install_ssh(release.get('VERSION_CODENAME', 'noble'), arch)
        configure_ssh()
        note('第 4/6 步：连接 Tailscale。')
        if not existing and not options.skip_login: login()
        note('第 5/6 步：保持验收期间机器唤醒。')
        if not existing:
            write('/etc/systemd/system/spark-bootstrap-awake.service', '[Unit]\nDescription=Keep Spark awake for remote acceptance\n[Service]\nExecStart=/usr/bin/systemd-inhibit --what=sleep --mode=block --why=Spark-remote-acceptance /usr/bin/sleep infinity\nRestart=on-failure\n[Install]\nWantedBy=multi-user.target\n', 0o644)
            run(['systemctl', 'daemon-reload'])
            run(['systemctl', 'enable', '--now', 'spark-bootstrap-awake.service'])
        note('第 6/6 步：检查连接状态和 SSH。')
        if options.skip_login: note('测试模式已跳过登录，尚未验证远程连接。')
        else: verify()


if __name__ == '__main__':
    try:
        main()
    except Failure as error:
        note(error.code + '：' + error.message + '\n下一步：' + error.action)
        sys.exit(2)
    except (OSError, ValueError, KeyError, TypeError) as error:
        code = 'E_DISK' if isinstance(error, OSError) and error.errno == 28 else 'E_CONFIG'
        note(code + '：安装文件或系统环境未能正确读取。\n下一步：请发送日志末尾，由远程操作人员处理后重跑。')
        if os.geteuid() == 0:
            with LOG.open('a') as stream: stream.write(clean(str(error)) + '\n')
        sys.exit(3)
