#!/usr/bin/env bash
# 在 Debian 或 Ubuntu 上配置和管理 HTTPS 反向隧道网关。
set -euo pipefail
export LC_ALL=C
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
umask 077

readonly DOMAIN_PREFIX=test-0 DOMAIN_SUFFIX=example.com SSH_HOST=192.0.2.10 SSH_PORT=22 LOCAL_HTTP_PORT=3000
readonly PORT_BASE=10000 LAST_ID=99 ACCOUNT=tunnel GROUP=tunnel
readonly SSH_SERVICE=ssh.service SSH_SOCKET=ssh.socket
readonly SSH_DIR=/etc/ssh/tunnel
readonly KEY_DIR=$SSH_DIR/authorized_keys
readonly AUTHORIZED_KEYS=$KEY_DIR/$ACCOUNT.keys
readonly SSH_MAIN_CONF=/etc/ssh/sshd_config
readonly SSH_CONFIG_DIR=/etc/ssh/sshd_config.d
readonly SSH_MATCH_CONF=$SSH_CONFIG_DIR/00-tunnel.conf
readonly WEB_DIR=/etc/nginx/tunnel
readonly MAP_FILE=$WEB_DIR/hosts.map
readonly NGINX_CONF=/etc/nginx/conf.d/tunnel.conf
readonly TLS_CERT=/etc/nginx/ssl/example.com_bundle.crt
readonly TLS_KEY=/etc/nginx/ssl/example.com.key
readonly STATE_DIR=/var/lib/tunnel
readonly READY=$STATE_DIR/numbered-ready
readonly ID_PATTERN='^[0-9]{2}$'
readonly KEY_PATTERN='^ssh-ed25519[[:blank:]]+([A-Za-z0-9+/]{68})([[:blank:]]|$)'
readonly REGISTERED_KEY_PATTERN='^ssh-ed25519 [A-Za-z0-9+/]{68}$'
declare -A slot_keys=()

usage() {
    cat <<'EOF'
在公网网关运行
  sudo bash tunnel.sh init
  sudo bash tunnel.sh add [公钥文件]
  sudo bash tunnel.sh add 01 [公钥文件]  # 为已有编号换钥
  sudo bash tunnel.sh del 01

init 前放行 TCP 22、443，保留管理员会话。DNS 和现有证书须覆盖编号域名。
  /etc/nginx/ssl/example.com_bundle.crt
  /etc/nginx/ssl/example.com.key

编号 01–99，域名前缀 test-0。01 对应 test-001.example.com 和网关端口 10001。
网关端口从 10001–10099 自动分配，内网服务监听 127.0.0.1:3000。
add 自动分配编号，省略 Ed25519 公钥文件时生成新密钥。
修正报错后重跑。已有待处理编号时，用 add 编号 [公钥文件] 继续，或用 del 编号 清理。
EOF
}

fail() {
    printf '错误：%s\n' "$*" >&2
    exit 1
}

atomic_write() {
    local target=$1 mode=$2 temporary
    temporary=$(mktemp -- "${target%/*}/.tunnel.XXXXXXXX") || return 1
    if ! cat > "$temporary" || ! chmod "$mode" "$temporary" ||
       ! mv -fT -- "$temporary" "$target"; then
        rm -f -- "$temporary"
        return 1
    fi
}

write_config_if_changed() {
    local target=$1 content=$2 current
    if [[ -f $target ]]; then
        current=$(<"$target") || fail "无法读取 $target。"
        [[ $content != "$current" ]] || return 0
    fi
    atomic_write "$target" 0644 <<< "$content" || fail "无法写入 $target。"
}

reload_nginx() {
    if systemctl is-active --quiet nginx.service; then
        systemctl reload nginx.service
    elif [[ ${1:-} != reload-only ]]; then
        systemctl start nginx.service
    fi
}

nginx_config() {
    local domain_pattern=${DOMAIN_SUFFIX//./[.]}
    cat <<EOF
# 由 tunnel.sh 生成。
map \$host \$tunnel_port {
    default "";
    include $MAP_FILE;
}

server {
    listen 443 ssl;
    server_name ~^$DOMAIN_PREFIX[0-9][0-9][.]$domain_pattern\$;
    ssl_certificate $TLS_CERT;
    ssl_certificate_key $TLS_KEY;
    ssl_protocols TLSv1.2 TLSv1.3;

    location / {
        if (\$tunnel_port = "") { return 404; }

        proxy_pass http://127.0.0.1:\$tunnel_port;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Forwarded-For \$remote_addr;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Forwarded-Prefix "";
        proxy_ignore_headers X-Accel-Redirect;
    }
}
EOF
}

install_packages() {
    local package statuses
    local -a packages=(nginx iproute2 python3) missing=()
    # 即使有包尚未安装，dpkg-query 仍会输出其余包的状态。
    statuses=$(dpkg-query -W -f='${Package}\t${Status}\n' "${packages[@]}" 2>/dev/null || true)
    statuses=$'\n'$statuses$'\n'
    for package in "${packages[@]}"; do
        [[ $statuses == *$'\n'"$package"$'\tinstall ok installed\n'* ]] || missing+=("$package")
    done
    if ((${#missing[@]})); then
        apt-get update && apt-get install -y "${missing[@]}" || fail '无法安装依赖。'
    fi
}

ssh_tunnel_config() {
    cat <<EOF
# 由 tunnel.sh 生成。
Match User $ACCOUNT
    AuthenticationMethods publickey
    PubkeyAuthentication yes
    AuthorizedKeysFile $AUTHORIZED_KEYS
    AuthorizedKeysCommand none
    TrustedUserCAKeys none
    MaxSessions 0
    AllowTcpForwarding remote
    AllowStreamLocalForwarding no
    GatewayPorts no
    PermitListen 127.0.0.1:*
    PermitTunnel no
    ClientAliveInterval 30
    LogLevel INFO
EOF
}

check_tunnel_account() {
    local effective lines rule
    effective=$(sshd -T -f "$SSH_MAIN_CONF" -C "user=$ACCOUNT,host=localhost,addr=127.0.0.1,laddr=127.0.0.1,lport=$SSH_PORT") ||
        fail "无法读取 $ACCOUNT 的 SSH 配置。"
    lines=$'\n'$effective$'\n'
    for rule in "authorizedkeysfile $AUTHORIZED_KEYS" 'authorizedkeyscommand none' 'trustedusercakeys none' 'loglevel INFO' \
        'pubkeyauthentication yes' 'authenticationmethods publickey' 'maxsessions 0' \
        'allowtcpforwarding remote' 'allowstreamlocalforwarding no' \
        'gatewayports no' 'permitlisten 127.0.0.1:*' 'permittunnel no' 'disableforwarding no'; do
        [[ $lines == *$'\n'"$rule"$'\n'* ]] || fail "$ACCOUNT 的 SSH 配置缺少 $rule，请运行 init。"
    done
    printf '%s\n' "$effective"
}

check_ssh_include_order() {
    local config
    # 专用账号规则必须先于其他可能优先匹配的条件规则加载。
    if ! awk -v pattern="$SSH_CONFIG_DIR/*.conf" '
        { sub(/#.*/, ""); gsub(/[[:space:]]*=[[:space:]]*/, " "); keyword = tolower($1); gsub(/^"|"$/, "", keyword) }
        keyword == "match" { exit }
        keyword == "include" { target = $2; gsub(/^"|"$/, "", target); found = (target == pattern); exit }
        END { exit !found }
    ' "$SSH_MAIN_CONF"; then
        fail "$SSH_MAIN_CONF 必须在其他 Include 或 Match 规则之前加载 $SSH_CONFIG_DIR/*.conf。"
    fi
    for config in "$SSH_CONFIG_DIR"/*.conf; do
        [[ -f $config && $config < $SSH_MATCH_CONF ]] || continue
        if grep -Eiq '^[[:space:]]*"?(include|match)"?([[:space:]=]|$)' "$config"; then
            fail "$config 中更早加载的 Include 或 Match 规则可能覆盖隧道权限。"
        fi
    done
}

prepare_sshd() {
    local listener uid
    if ! systemctl is-active --quiet "$SSH_SERVICE" && ! systemctl is-active --quiet "$SSH_SOCKET"; then
        fail "请先启动 SSH 服务或套接字，再运行 init。"
    fi
    listener=$(ss -H -ltn "sport = :$SSH_PORT") || fail '无法检查 SSH 监听端口。'
    [[ -n $listener ]] || fail "系统 SSH 服务必须已监听 $SSH_PORT 端口。"
    check_ssh_include_order
    uid=$(tunnel_uid) || return 1
    if [[ -z $uid ]]; then
        getent group "$GROUP" >/dev/null || groupadd --system "$GROUP" || fail "无法创建用户组 $GROUP。"
        useradd --no-create-home --no-user-group --no-log-init --gid "$GROUP" \
            --home-dir /nonexistent --shell /usr/sbin/nologin --comment "$GROUP" "$ACCOUNT" ||
            fail "无法创建 SSH 账号 $ACCOUNT。"
    fi
    install -d -m 0755 -o root -g root "$SSH_CONFIG_DIR" /run/sshd || fail '无法准备 SSH 目录。'
}

show_ssh_fingerprints() {
    local entry
    printf 'SSH 主机指纹\n'
    while IFS= read -r entry; do
        if [[ $entry == 'hostkey '* && -r ${entry#hostkey } ]]; then
            ssh-keygen -lf "${entry#hostkey }" || printf '请检查 SSH 配置中的主机密钥。\n' >&2
        fi
    done <<< "$1"
}

init_environment() {
    local effective
    install_packages
    prepare_sshd || return 1
    install -d -m 0755 -o root -g root "$SSH_DIR" "$KEY_DIR" || fail '无法准备 SSH 授权目录。'
    install -d -m 0755 -o root -g root "$WEB_DIR" || fail "无法创建 $WEB_DIR。"
    load_slots

    rm -f -- "$READY" || fail '无法重置初始化状态。'
    render_active_slots ssh | atomic_write "$AUTHORIZED_KEYS" 0644 || fail "无法写入 $AUTHORIZED_KEYS。"
    render_active_slots nginx | atomic_write "$MAP_FILE" 0644 || fail "无法写入 $MAP_FILE。"
    ssh_tunnel_config | atomic_write "$SSH_MATCH_CONF" 0644 || fail "无法写入 $SSH_MATCH_CONF。"
    nginx_config | atomic_write "$NGINX_CONF" 0644 || fail "无法写入 $NGINX_CONF。"

    effective=$(check_tunnel_account) || return 1
    nginx -t || fail 'Nginx 配置校验失败，请重试 init。'

    reload_nginx || fail 'Nginx 启动或重载失败，请重试 init。'
    # 使用套接字激活时，SSH 服务会在启动时读取新配置。
    if systemctl is-active --quiet "$SSH_SERVICE"; then
        systemctl reload "$SSH_SERVICE" || fail 'SSH 重载失败，请重试 init。'
    fi
    systemctl enable nginx.service || fail '无法启用 Nginx 服务。'
    show_ssh_fingerprints "$effective"
    touch -- "$READY" || fail '无法保存初始化状态。'
    printf '初始化完成。\n'
}

read_public_key() {
    local file=$1 line key
    [[ -f $file ]] || fail "找不到公钥文件 $file。"
    # 只接受一行纯 Ed25519 公钥，丢弃公钥末尾的注释。
    line=$(<"$file") || fail "无法读取公钥文件 $file。"
    line=${line%$'\r'}
    [[ $line != *$'\n'* && $line =~ $KEY_PATTERN ]] || fail '公钥文件须包含一行 Ed25519 公钥。'
    key="ssh-ed25519 ${BASH_REMATCH[1]}"
    ssh-keygen -lf - <<< "$key" >/dev/null || fail 'Ed25519 公钥无效。'
    printf '%s\n' "$key"
}

tunnel_uid() {
    local account status uid shell
    account=$(getent passwd "$ACCOUNT") || {
        status=$?
        ((status == 2)) || fail "无法查询 SSH 账号 $ACCOUNT。"
        return 0
    }
    IFS=: read -r _ _ uid _ _ _ shell <<< "$account"
    [[ $uid =~ ^[1-9][0-9]*$ && $shell == /usr/sbin/nologin ]] ||
        fail "专用账号 $ACCOUNT 须使用非零 UID 和 nologin。"
    printf '%s\n' "$uid"
}

check_id() {
    [[ $1 =~ $ID_PATTERN && $1 != 00 ]] || fail '隧道编号必须在 01 至 99 之间。'
}

load_slots() {
    local file id key
    slot_keys=()
    for file in "$STATE_DIR"/[0-9][0-9].{pub,pending}; do
        [[ -e $file || -L $file ]] || continue
        id=${file##*/}
        id=${id%.*}
        check_id "$id"
        [[ -f $file && ! -L $file ]] || fail "登记文件 $file 的类型异常。"
        [[ ! ${slot_keys[$id]+present} ]] || fail "编号 $id 同时存在两份登记。"
        key=$(<"$file") || fail "无法读取登记文件 $file。"
        [[ $key =~ $REGISTERED_KEY_PATTERN ]] || fail "登记文件 $file 格式无效。"
        slot_keys[$id]=$key
    done
}

render_active_slots() {
    local output=$1 publishing=${2-} file id port
    for file in "$STATE_DIR"/[0-9][0-9].*; do
        id=${file##*/}
        id=${id%.*}
        [[ ${slot_keys[$id]+present} ]] || continue
        # 只有正在发布的编号可以使用待处理记录。
        [[ $file == *.pub || ( $file == *.pending && $id == "$publishing" ) ]] || continue
        port=$((PORT_BASE + 10#$id))
        case $output in
            ssh) printf 'restrict,port-forwarding,permitlisten="127.0.0.1:%d" %s\n' "$port" "${slot_keys[$id]}" ;;
            nginx) printf '%s%s.%s %d;\n' "$DOMAIN_PREFIX" "$id" "$DOMAIN_SUFFIX" "$port" ;;
        esac
    done
}

publish_keys() {
    local content
    content=$(render_active_slots ssh "${1-}")
    write_config_if_changed "$AUTHORIZED_KEYS" "$content"
}

publish_routes() {
    write_config_if_changed "$MAP_FILE" "$(render_active_slots nginx "${2-}")"
    # 即使映射相同也执行，补上上次可能失败的重载。
    nginx -t && reload_nginx "${1-}" || fail 'Nginx 路由加载失败。'
}

allocate_id() {
    local number candidate listening address
    local -A occupied=()
    listening=$(ss -H -ltn) || fail '无法检查网关监听端口。'
    while read -r _ _ _ address _; do
        [[ $address == *:* ]] || continue
        occupied[${address##*:}]=1
    done <<< "$listening"
    for ((number=1; number<=LAST_ID; number++)); do
        printf -v candidate '%02d' "$number"
        [[ ! ${slot_keys[$candidate]+present} && ! ${occupied[$((PORT_BASE + number))]+present} ]] || continue
        printf '%s\n' "$candidate"
        return 0
    done
    fail '没有可用的隧道编号。'
}

generate_key_pair() (
    set +x +a
    local key_file=$1 host=$2 passphrase confirmation result
    export -n passphrase confirmation
    while :; do
        if ! IFS= read -r -s -p '私钥口令（可留空） ' passphrase; then
            printf '\n' >&2
            fail '口令输入已结束。'
        fi
        printf '\n' >&2
        if ! IFS= read -r -s -p '确认口令 ' confirmation; then
            printf '\n' >&2
            fail '口令输入已结束。'
        fi
        printf '\n' >&2
        [[ $passphrase == "$confirmation" ]] && break
        printf '口令不一致，请重输。\n' >&2
    done
    # 通过管道输入口令，并让 ssh-keygen 在没有控制终端的会话中读取。
    if ! result=$(printf '%s\n%s\n' "$passphrase" "$confirmation" |
        SSH_ASKPASS_REQUIRE=never setsid --wait ssh-keygen -q -t ed25519 -a 64 -C "$host" -f "$key_file" 2>&1); then
        printf '%s\n' "$result" >&2
        fail '生成 SSH 密钥失败。'
    fi
)

# 授权撤销后，按成功认证的指纹识别连接，包括尚未创建 -R 监听器的连接。
stop_key_sessions() {
    local key=$1
    python3 - "$ACCOUNT" "$key" <<'PYTHON'
import base64
import contextlib
import hashlib
import json
import os
from pathlib import Path
import pwd
import re
import select
import signal
import subprocess
import sys

account, key = sys.argv[1:]
account_uid = pwd.getpwnam(account).pw_uid
proc = Path("/proc")
blob = base64.b64decode(key.split()[1], validate=True)
sha256 = base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
md5 = hashlib.md5(blob, usedforsecurity=False).digest().hex(":")
fingerprints = {"SHA256:" + sha256, "MD5:" + md5}
title = re.compile(rb"sshd(?:-session)?: " + re.escape(account.encode()) + rb" \[priv\]")
accepted = re.compile(
    r"Accepted publickey for " + re.escape(account)
    + r" from \S+ port \d+ ssh2: ED25519 ((?:SHA256|MD5):\S+)(?:\s|$)"
)
ticks = os.sysconf("SC_CLK_TCK")

def stat(pid):
    return (proc / str(pid) / "stat").read_text().rsplit(")", 1)[1].split()

def effective_uid(entry):
    for line in (entry / "status").read_text().splitlines():
        if line.startswith("Uid:"):
            return int(line.split()[2])
    raise RuntimeError(f"无法确认进程 {entry.name} 的身份。")

def exited(fd, timeout_ms=0):
    poll = select.poll()
    poll.register(fd, select.POLLIN)
    return bool(poll.poll(timeout_ms))

def send(fd, sig):
    with contextlib.suppress(ProcessLookupError):
        signal.pidfd_send_signal(fd, sig)

def stop(pid, fd):
    # 暂停已确认的监控进程，取得该连接的子进程后再一起关闭。
    send(fd, signal.SIGSTOP)
    try:
        for _ in range(50):
            if exited(fd, 20):
                return
            if stat(pid)[0] in ("T", "t"):
                break
        else:
            raise RuntimeError(f"无法暂停 SSH 连接进程 {pid}。")
        children = (proc / str(pid) / "task" / str(pid) / "children").read_text().split()
        with contextlib.ExitStack() as stack:
            child_fds = []
            for child in map(int, children):
                with contextlib.suppress(FileNotFoundError, ProcessLookupError):
                    child_fd = os.pidfd_open(child)
                    stack.callback(os.close, child_fd)
                    if stat(child)[1] == str(pid):
                        child_fds.append(child_fd)
            for target_fd in [*child_fds, fd]:
                send(target_fd, signal.SIGTERM)
            send(fd, signal.SIGCONT)
            for target_fd in [fd, *child_fds]:
                if not exited(target_fd, 1500):
                    send(target_fd, signal.SIGKILL)
                if not exited(target_fd, 500):
                    raise RuntimeError(f"SSH 连接进程 {pid} 尚未关闭。")
    except FileNotFoundError:
        if not exited(fd):
            raise
    finally:
        send(fd, signal.SIGCONT)

def main():
    # 先取快照，再同步认证日志。公钥读取发生在 OpenSSH 设置进程标题之后。
    with contextlib.ExitStack() as stack:
        monitors = {}
        workers = []
        for entry in proc.iterdir():
            if not entry.name.isdecimal():
                continue
            with contextlib.suppress(FileNotFoundError, ProcessLookupError):
                if (entry / "comm").read_text().strip() not in ("sshd", "sshd-session"):
                    continue
                owner = effective_uid(entry)
                if owner not in (0, account_uid):
                    continue
                cmdline = (entry / "cmdline").read_bytes().split(b"\0", 1)[0]
                if owner == 0 and not title.fullmatch(cmdline):
                    continue
                pid = int(entry.name)
                fd = os.pidfd_open(pid)
                stack.callback(os.close, fd)
                if exited(fd) or effective_uid(entry) != owner:
                    continue
                fields = stat(pid)
                if owner == account_uid:
                    workers.append((fd, int(fields[1])))
                elif title.fullmatch((entry / "cmdline").read_bytes().split(b"\0", 1)[0]):
                    monitors[pid] = (fd, int(fields[19]) * 1_000_000 // ticks)
        if any(parent not in monitors and not exited(fd) for fd, parent in workers):
            raise RuntimeError("无法确认 tunnel 连接的监控进程。")
        if not monitors:
            return

        subprocess.run(["journalctl", "--sync"], check=True, timeout=10)
        log = subprocess.run(
            ["journalctl", "-b", "--quiet", "--no-pager", "-o", "json",
             "--output-fields=MESSAGE,_PID,__MONOTONIC_TIMESTAMP", "_UID=0"]
            + [f"_PID={pid}" for pid in monitors],
            check=True, capture_output=True, text=True, timeout=15,
        )
        identities = {}
        for line in log.stdout.splitlines():
            event = json.loads(line)
            pid = int(event["_PID"])
            message = event.get("MESSAGE", "")
            match = accepted.match(message) if isinstance(message, str) else None
            if match and int(event["__MONOTONIC_TIMESTAMP"]) >= monitors[pid][1]:
                identities[pid] = match[1]

        unknown = []
        for pid, (fd, _) in monitors.items():
            if exited(fd):
                continue
            fingerprint = identities.get(pid)
            if fingerprint in fingerprints:
                stop(pid, fd)
            elif fingerprint is None:
                unknown.append(pid)
        if any(not exited(monitors[pid][0]) for pid in unknown):
            raise RuntimeError("存在尚未确认公钥的 tunnel 连接。")

try:
    main()
except (OSError, ValueError, KeyError, RuntimeError, subprocess.SubprocessError) as error:
    sys.exit(str(error))
PYTHON
}

retire_slot() {
    local id=$1
    if [[ -f $STATE_DIR/$id.pub ]]; then
        mv -T -- "$STATE_DIR/$id.pub" "$STATE_DIR/$id.pending" || fail "无法撤销编号 $id 的登记。"
    fi
    publish_keys
    publish_routes reload-only
    stop_key_sessions "${slot_keys[$id]}" || fail "旧连接未确认关闭，保留编号 $id。请重试。"
}

clear_key_stage() {
    local id=$1 directory=$STATE_DIR/.$1
    [[ ! -L $directory ]] || fail "临时密钥目录 $directory 的类型异常。"
    [[ -e $directory ]] || return 0
    rm -f -- "$directory/$id" "$directory/$id.pub" &&
        rmdir -- "$directory" || fail "无法清理临时密钥目录 $directory。"
}

add_tunnel() (
    local id=$1 public_file=$2 key other key_stage='' port host listening
    if [[ -n $id ]]; then
        [[ ${slot_keys[$id]+present} ]] || fail "编号 $id 未登记。新建时省略编号。"
    else
        id=$(allocate_id) || exit 1
    fi
    port=$((PORT_BASE + 10#$id))
    host=$DOMAIN_PREFIX$id.$DOMAIN_SUFFIX

    if [[ -z $public_file ]]; then
        key_stage=$STATE_DIR/.$id
        clear_key_stage "$id"
        mkdir -- "$key_stage" || fail '无法准备临时密钥目录。'
        trap 'clear_key_stage "$id"' EXIT
        generate_key_pair "$key_stage/$id" "$host" || exit 1
        chmod 0600 "$key_stage/$id" || fail '无法限制私钥访问权限。'
        public_file=$key_stage/$id.pub
    fi
    key=$(read_public_key "$public_file") || exit 1
    for other in "${!slot_keys[@]}"; do
        [[ $other == "$id" || ${slot_keys[$other]} != "$key" ]] ||
            fail "该公钥已登记在编号 $other。"
    done

    printf '编号  %s\n' "$id"
    [[ -n $key_stage ]] || clear_key_stage "$id"
    if [[ -n $key_stage || ! -f $STATE_DIR/$id.pub || ${slot_keys[$id]-} != "$key" ]]; then
        if [[ ${slot_keys[$id]+present} ]]; then
            retire_slot "$id"
            if ! listening=$(ss -H -ltn "sport = :$port") || [[ -n $listening ]]; then
                fail "网关端口 $port 未确认空闲，请处理后重试 add $id。"
            fi
        fi
        atomic_write "$STATE_DIR/$id.pending" 0600 <<< "$key" || fail "无法保存编号 $id 的登记。"
        slot_keys[$id]=$key
        if [[ -n $key_stage ]]; then
            mv -fT -- "$key_stage/$id" "$STATE_DIR/$id" || fail "无法保存编号 $id 的私钥。"
        else
            rm -f -- "$STATE_DIR/$id" || fail "无法删除编号 $id 的旧私钥。"
        fi
    fi
    publish_routes '' "$id"
    publish_keys "$id"
    if [[ -f $STATE_DIR/$id.pending ]]; then
        mv -T -- "$STATE_DIR/$id.pending" "$STATE_DIR/$id.pub" || fail "无法完成编号 $id 的登记。"
    fi

    printf '访问  https://%s/\n' "$host"
    if [[ -n $key_stage ]]; then
        printf '网关私钥  %s/%s\n' "$STATE_DIR" "$id"
    fi
    cat <<EOF
内网连接（-i 指向私钥，首次可临时设 StrictHostKeyChecking=ask 并核对 init 输出的指纹）
ssh -N -p $SSH_PORT -i "\$HOME/.ssh/$id" -o IdentitiesOnly=yes -o StrictHostKeyChecking=yes -o ExitOnForwardFailure=yes -o ServerAliveInterval=30 -o ServerAliveCountMax=3 -R 127.0.0.1:$port:127.0.0.1:$LOCAL_HTTP_PORT $ACCOUNT@$SSH_HOST
EOF
)

remove_tunnel() {
    local id=$1
    if [[ ${slot_keys[$id]+present} ]]; then
        retire_slot "$id"
    fi
    clear_key_stage "$id"
    rm -f -- "$STATE_DIR/$id" || fail "无法删除编号 $id 的私钥。"
    rm -f -- "$STATE_DIR/$id.pending" || fail "无法释放编号 $id。"
    printf '已删除隧道 %s。\n' "$id"
}

main() {
    local command=${1:-help} id='' public_file='' uid
    case $command in
        help|-h|--help) usage; return ;;
        init)
            [[ $# == 1 ]] || fail '用法为 init。'
            ;;
        add)
            [[ $# -le 3 ]] || fail '用法为 add [公钥文件] 或 add 已有编号 [公钥文件]。'
            if [[ $# == 3 ]]; then
                check_id "$2"
                id=$2
                public_file=$3
                [[ -n $public_file ]] || fail '公钥文件路径不能为空。'
            elif [[ $# == 2 && $2 =~ $ID_PATTERN ]]; then
                check_id "$2"
                id=$2
            elif [[ $# == 2 ]]; then
                public_file=$2
                [[ -n $public_file && ! $public_file =~ ^[0-9]+$ ]] || fail '请输入公钥文件路径。'
            fi
            ;;
        del)
            [[ $# == 2 ]] || fail '用法为 del 编号。'
            check_id "$2"
            id=$2
            ;;
        *) fail "未知命令 $command，请查看 --help。" ;;
    esac
    [[ $EUID == 0 ]] || fail '请使用 sudo 或以 root 身份运行。'
    [[ -f /etc/debian_version && -d /run/systemd/system ]] || fail '请在使用 systemd 的 Debian 或 Ubuntu 网关上运行。'
    [[ ! -L $STATE_DIR ]] || fail "状态目录 $STATE_DIR 的类型异常。"
    if [[ $command == init ]]; then
        install -d -m 0700 -o root -g root "$STATE_DIR" || fail '无法创建隧道状态目录。'
    fi
    [[ -d $STATE_DIR ]] || fail '请先在公网网关运行 init。'
    exec 9<"$STATE_DIR" || fail '无法打开隧道状态目录。'
    flock -x 9 || fail '无法锁定隧道状态目录。'
    if [[ $command == init ]]; then
        init_environment
        return
    fi
    [[ -f $READY ]] || fail '请先在公网网关运行 init。'
    uid=$(tunnel_uid) || return 1
    [[ -n $uid ]] || fail '找不到专用账号，请先运行 init。'
    load_slots
    case $command in
        add)
            check_ssh_include_order
            check_tunnel_account >/dev/null
            add_tunnel "$id" "$public_file"
            ;;
        del) remove_tunnel "$id" ;;
    esac
}

main "$@"
