#!/bin/bash

SCRIPT_VERSION="devel/1.0.0.0-0k7.0"

# 早期参数扫描：--help / -h 免 sudo 放行（符合 POSIX 惯例）
for _arg in "$@"; do
    case "$_arg" in
        -h|--help)
            cat <<EOF
kylin-software-center-saveLog v${SCRIPT_VERSION}

本脚本必须以 root 权限运行（/var/log/kylin-system-updater/ 等系统日志需 root 读取）。

基本用法:
    sudo $0 [选项]

查看完整帮助（需在 sudo 下运行）:
    sudo $0 --help
EOF
            exit 0
            ;;
    esac
done

# 强制 root 权限检查
if [ "$(id -u)" -ne 0 ]; then
    echo "错误: 本脚本必须以 root 权限运行（/var/log/kylin-system-updater/ 等系统日志需 root 读取）" >&2
    echo "请使用: sudo $0 $*" >&2
    exit 1
fi

# 识别真实调用者（仅支持 sudo 调用；su -/pkexec/直接 root 登录无法识别原用户）
REAL_USER="${SUDO_USER:-}"
if [ -z "$REAL_USER" ]; then
    echo "错误: 无法识别调用者。请使用 'sudo $0'，而非 su -/pkexec/直接 root 登录" >&2
    exit 1
fi
HOME_DIR="/home/$REAL_USER"
if [ ! -d "$HOME_DIR" ]; then
    echo "错误: 调用者家目录 $HOME_DIR 不存在" >&2
    exit 1
fi

# 定义日志文件路径（basic 级别默认收集）
LOG_FILES=(
    "$HOME_DIR/.cache/uksc/"
    "/var/log/kylin-system-updater/"
    "/opt/compatibility_layer/logs/"
    "/var/log/kare/"
    "/etc/kylin-build"
    "/etc/kylin-version/"
    "/etc/os-release"
    "/etc/lsb-release"
    "/var/log/kaiming.log"
    "/etc/apt/sources.list"
    "/var/log/dpkg.log"
    "/etc/environment"
    "/etc/profile.d/"
    "$HOME_DIR/.pam_environment"
    "/etc/hosts"
    "/var/log/syslog"
    "/var/log/syslog.1"
    "/etc/kylin-config/"
)

# 默认跳过大目录（通过参数可开启收集）
SKIP_DIRS=(
    "$HOME_DIR/.cache/uksc/wget_down/"
    "$HOME_DIR/.cache/uksc/icons/"
    "$HOME_DIR/.cache/uksc/ads/"
    "$HOME_DIR/.cache/uksc/coverimage/"
    "$HOME_DIR/.cache/uksc/imagecode/"
    "$HOME_DIR/.cache/uksc/previewImage/"
)

# ===== 额外参数（默认不开启）=====
INCLUDE_APT_DIR=0
INCLUDE_COREDUMP=0
INCLUDE_ICON_DIRS=0
INCLUDE_DEB=0
INCLUDE_APT_REPO_LIST=0
DRY_RUN=0
COLLECT_LEVEL="basic"

# ===== 统计计数器 =====
STAT_COPIED=0
STAT_SKIPPED=0
STAT_COREDUMP=0
STAT_CMD_SAVED=0

print_usage() {
    cat <<EOF
用法: sudo $0 [选项]

权限要求:
  必须使用 sudo 运行（/var/log/kylin-system-updater/ 等系统日志需 root 读取）。
  脚本会自动通过 \$SUDO_USER 识别调用者，收集该用户家目录下的软件商店缓存。
  请勿使用 su -/pkexec/直接 root 登录等方式运行（无法识别原用户）。

默认收集（无需任何参数）:
  • 软件商店运行日志与调用者用户缓存 (/home/<SUDO_USER>/.cache/uksc/)
  • 系统版本信息 (/etc/kylin-build, /etc/os-release 等)
  • apt/dpkg 状态与操作日志
  • 环境变量配置
  • coredump 调用栈 (backtrace)
  • 软件环境信息 (dpkg -l, kare -l, kaiming list 等)
  • /etc/kylin-config/ 配置目录（默认排除 .git/.cache/backups）

收集级别:
  -l, --level <级别>    设置收集级别（默认: basic）
      basic             基础级别（默认）: 快速收集，体积小
      standard          标准级别: 基础 + /var/lib/apt/ + coredump原始文件 + 图标缓存
      full              完整级别: 标准 + deb安装包 + apt仓库列表（耗时较长）

高级选项（可与 --level 叠加使用）:
  --include-apt-dir     单独开启: 收集 /var/lib/apt/ 目录
  --include-coredump    单独开启: 收集 coredump 原始文件
  --include-icons       单独开启: 收集图标/广告/图片缓存
  --include-deb         单独开启: 收集下载的 deb 包
  --include-apt-repo-list   单独开启: 收集 apt 仓库列表（耗时较长）
  --dry-run             预览模式: 只展示将收集的内容，不实际执行
  -h, --help            显示此帮助（免 sudo）

示例:
  sudo $0                          # 基础收集（推荐，多数场景够用）
  sudo $0 --level standard         # 标准收集
  sudo $0 --level full             # 全量收集
  sudo $0 --include-apt-dir        # 基础 + 额外收集 /var/lib/apt/
  sudo $0 --dry-run                # 预览将收集的内容
  sudo $0 --dry-run --level full   # 预览全量收集的内容

提示: 也可以给脚本加执行权限后直接运行:
  chmod +x $0 && sudo ./$0
EOF
}

parse_args() {
    while [ $# -gt 0 ]; do
        case "$1" in
            -l|--level)
                if [ -z "$2" ] || [[ "$2" == -* ]]; then
                    echo "错误: --level 需要指定级别 (basic/standard/full)" >&2
                    print_usage >&2
                    exit 2
                fi
                case "$2" in
                    basic)    COLLECT_LEVEL="basic" ;;
                    standard) COLLECT_LEVEL="standard" ;;
                    full)     COLLECT_LEVEL="full" ;;
                    *)
                        echo "错误: 未知级别 '$2'，可选: basic / standard / full" >&2
                        print_usage >&2
                        exit 2
                        ;;
                esac
                shift 2
                ;;
            --include-apt-dir)
                INCLUDE_APT_DIR=1
                shift
                ;;
            --include-deb)
                INCLUDE_DEB=1
                shift
                ;;
            --include-coredump)
                INCLUDE_COREDUMP=1
                shift
                ;;
            --include-icons)
                INCLUDE_ICON_DIRS=1
                shift
                ;;
            --include-apt-repo-list)
                INCLUDE_APT_REPO_LIST=1
                shift
                ;;
            --dry-run)
                DRY_RUN=1
                shift
                ;;
            -h|--help)
                print_usage
                exit 0
                ;;
            *)
                echo "未知选项: $1" >&2
                print_usage >&2
                exit 2
                ;;
        esac
    done
}

remove_skip_dir() {
    local target="$1"
    local new_list=()
    local item=""
    for item in "${SKIP_DIRS[@]}"; do
        if [ "$item" != "$target" ]; then
            new_list+=("$item")
        fi
    done
    SKIP_DIRS=("${new_list[@]}")
}

apply_extra_options() {
    # 根据收集级别设置各开关（级别是叠加的，高级别包含低级别）
    case "$COLLECT_LEVEL" in
        standard)
            INCLUDE_APT_DIR=1
            INCLUDE_COREDUMP=1
            INCLUDE_ICON_DIRS=1
            ;;
        full)
            INCLUDE_APT_DIR=1
            INCLUDE_COREDUMP=1
            INCLUDE_ICON_DIRS=1
            INCLUDE_DEB=1
            INCLUDE_APT_REPO_LIST=1
            ;;
        # basic: 不额外开启任何选项
    esac

    # 需要收集 /var/lib/apt/：动态添加到 LOG_FILES
    if [ "$INCLUDE_APT_DIR" -eq 1 ]; then
        LOG_FILES+=("/var/lib/apt/")
    fi

    # 需要收集 deb 包：从 SKIP_DIRS 中移除 wget_down
    if [ "$INCLUDE_DEB" -eq 1 ]; then
        remove_skip_dir "$HOME_DIR/.cache/uksc/wget_down/"
    fi

    # 需要收集 icon/ads/图片缓存：从 SKIP_DIRS 中移除对应目录
    if [ "$INCLUDE_ICON_DIRS" -eq 1 ]; then
        remove_skip_dir "$HOME_DIR/.cache/uksc/icons/"
        remove_skip_dir "$HOME_DIR/.cache/uksc/ads/"
        remove_skip_dir "$HOME_DIR/.cache/uksc/coverimage/"
        remove_skip_dir "$HOME_DIR/.cache/uksc/imagecode/"
        remove_skip_dir "$HOME_DIR/.cache/uksc/previewImage/"
    fi
}

# 获取当前时间戳
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')

# 尝试获取软件商店版本号，嵌入到压缩包文件名中
UKSC_VERSION=""
if command -v dpkg-query >/dev/null 2>&1; then
    UKSC_VERSION=$(dpkg-query -W -f='${Version}' kylin-software-center 2>/dev/null || true)
elif command -v dpkg >/dev/null 2>&1; then
    UKSC_VERSION=$(dpkg -l 2>/dev/null | grep -oP '^ii\s+kylin-software-center\s+\K\S+' | head -1)
fi
VERSION_TAG=""
if [ -n "$UKSC_VERSION" ]; then
    VERSION_TAG="_v${UKSC_VERSION}"
fi

# 创建临时日志存储文件夹
ARCHIVE_DIR="/tmp/kylin-software-center-log_archive_$TIMESTAMP"
ARCHIVE_FILE="/tmp/kylin-software-center-logs${VERSION_TAG}_$TIMESTAMP.tar.gz"
RUNTIME_LOG="$ARCHIVE_DIR/collect_runtime.log"

# 日志函数：同时输出到终端和运行时日志文件
log() {
    local message="$1"
    local line="$(date '+%Y-%m-%d %H:%M:%S') - $message"
    echo "$line"
    # 如果 ARCHIVE_DIR 已创建，同时写入运行时日志
    if [ -d "$ARCHIVE_DIR" ]; then
        echo "$line" >> "$RUNTIME_LOG"
    fi
}

# 检查并创建目录
create_directory() {
    local dir="$1"
    if [ ! -d "$dir" ]; then
        mkdir -p "$dir"
        if [ $? -ne 0 ]; then
            log "Failed to create directory: $dir"
            exit 1
        fi
    fi
}

copy_log_files() {
    # 构建 --exclude 参数
    # 注意: rsync -R 模式下 --exclude 匹配的是相对传输路径，
    # 需要用 basename 模式而非绝对路径
    EXCLUDE_ARGS=()
    for skip in "${SKIP_DIRS[@]}"; do
        local skip_basename
        # 去掉末尾的 / 后取 basename，如 /home/user/.cache/uksc/wget_down/ -> wget_down
        skip_basename=$(basename "${skip%/}")
        EXCLUDE_ARGS+=(--exclude="*/${skip_basename}/***" --exclude="${skip_basename}/***")
    done

    for LOG_FILE in "${LOG_FILES[@]}"; do
        if [ -e "$LOG_FILE" ]; then
            local rsync_output=""
            # /etc/kylin-config/ 可能含 .git/.cache/backups 等大体积子目录，单独排除
            local extra_exclude=()
            case "$LOG_FILE" in
                /etc/kylin-config|/etc/kylin-config/*)
                    extra_exclude+=(
                        --exclude='.git' --exclude='*/.git/***'
                        --exclude='.cache' --exclude='*/.cache/***'
                        --exclude='backups' --exclude='*/backups/***'
                    )
                    ;;
            esac
            if ! rsync_output=$(rsync -aRL "${EXCLUDE_ARGS[@]}" "${extra_exclude[@]}" "$LOG_FILE" "$ARCHIVE_DIR" 2>&1); then
                log "Failed to copy log file or directory: $LOG_FILE; reason: $rsync_output"
            else
                STAT_COPIED=$((STAT_COPIED + 1))
            fi
        else
            STAT_SKIPPED=$((STAT_SKIPPED + 1))
            log "Log file or directory does not exist: $LOG_FILE"
        fi
    done
}

# 打包日志文件
# 打包日志文件（优先使用高效压缩：zstd > pigz > gzip）
archive_logs() {
    # if command -v zstd >/dev/null 2>&1; then
    #     # zstd: 压缩率与 gzip 相当，速度快数倍
    #     ARCHIVE_FILE="${ARCHIVE_FILE%.tar.gz}.tar.zst"
    #     tar -cf - -C "$ARCHIVE_DIR" . | zstd -T0 -o "$ARCHIVE_FILE"
    #     log "Using zstd compression"
    # elif command -v pigz >/dev/null 2>&1; then
    #     # pigz: 多线程 gzip 兼容压缩
    #     tar -cf - -C "$ARCHIVE_DIR" . | pigz > "$ARCHIVE_FILE"
    #     log "Using pigz compression"
    # else
    #     # 回退到标准 gzip
    #     tar -czf "$ARCHIVE_FILE" -C "$ARCHIVE_DIR" .
    #     log "Using gzip compression"
    # fi
    tar -czvf "$ARCHIVE_FILE" -C "$ARCHIVE_DIR" .
    if [ $? -ne 0 ]; then
        log "Failed to create archive: $ARCHIVE_FILE"
        exit 1
    fi
}

# 将归档文件拷贝一份到桌面（以真实用户身份复制，确保权限正确）
DESKTOP_COPY_STATUS=""
copy_archive_to_desktop() {
    # 通过 getent 拿到真实用户的家目录（不依赖 $HOME，避免 sudo 下 $HOME=/root）
    local real_home=""
    real_home=$(getent passwd "$REAL_USER" 2>/dev/null | awk -F: '{print $6}')
    if [ -z "$real_home" ] || [ ! -d "$real_home" ]; then
        DESKTOP_COPY_STATUS="未找到 $REAL_USER 的家目录"
        log "Home directory of $REAL_USER not found"
        return 0
    fi

    # 按优先级查找桌面目录：中文 桌面 -> 英文 Desktop -> xdg-user-dir
    local desktop_dir=""
    if [ -d "$real_home/桌面" ]; then
        desktop_dir="$real_home/桌面"
    elif [ -d "$real_home/Desktop" ]; then
        desktop_dir="$real_home/Desktop"
    elif command -v xdg-user-dir >/dev/null 2>&1; then
        # 通过 sudo -u 调用 xdg-user-dir，确保拿到真实用户的桌面路径（而非 root 的）
        desktop_dir=$(sudo -u "$REAL_USER" xdg-user-dir DESKTOP 2>/dev/null || true)
        [ -d "$desktop_dir" ] || desktop_dir=""
    fi

    if [ -z "$desktop_dir" ]; then
        DESKTOP_COPY_STATUS="未找到桌面目录"
        log "Desktop directory not found under $real_home"
        return 0
    fi

    # 以真实用户身份复制，压缩包所有权天然为该用户（用户可读可删）
    if sudo -u "$REAL_USER" cp -f "$ARCHIVE_FILE" "$desktop_dir/"; then
        DESKTOP_COPY_STATUS="已复制到 $desktop_dir/ ($REAL_USER)"
        log "Archive copied to Desktop: $desktop_dir (owner: $REAL_USER)"
    else
        DESKTOP_COPY_STATUS="复制失败（磁盘空间不足？）"
        log "Failed to copy archive to Desktop (disk full?)"
    fi
}

# 清理临时目录
cleanup() {
    rm -rf "$ARCHIVE_DIR"
    if [ $? -ne 0 ]; then
        log "Warning: Failed to clean up directory: $ARCHIVE_DIR"
    fi
}

# 新增函数：根据文件名包含的字符串将文件路径添加到LOG_FILES数组中
add_files_with_string_to_log_files() {
    local dir="$1"
    local search_str="$2"

    if [ -d "$dir" ]; then
        while IFS= read -r -d '' file; do
            LOG_FILES+=("$file")
        done < <(find "$dir" -maxdepth 5 -type f -name "*$search_str*" -print0)
    else
        log "Directory does not exist: $dir"
    fi
}

collect_coredump_backtraces() {
    local output_dir="$1"
    local output_file="coredump_backtrace.log"
    local list_file="coredump_list.log"
    local output_path="$output_dir/$output_file"
    local list_path="$output_dir/$list_file"
    local gdb_timeout=60  # 每个 PID 的 gdb 超时秒数

    create_directory "$output_dir"

    if ! command -v coredumpctl >/dev/null 2>&1; then
        log "coredumpctl not found, skip coredump backtrace"
        return 0
    fi

    # 检测 coredumpctl 是否支持 --all 参数
    local coredumpctl_supports_all=0
    if coredumpctl --help 2>&1 | grep -q -- '--all'; then
        coredumpctl_supports_all=1
    fi

    local has_gdb=1
    if ! command -v gdb >/dev/null 2>&1; then
        has_gdb=0
        log "gdb not found, will save coredumpctl info instead"
    fi

    local has_timeout=0
    if command -v timeout >/dev/null 2>&1; then
        has_timeout=1
    fi

    coredumpctl list --no-legend 2>/dev/null > "$list_path"
    local dump_list
    dump_list=$(grep -E "software-center|kylin-software" "$list_path" || true)
    if [ -z "$dump_list" ]; then
        log "No coredump matched (software-center/kylin-software); see $list_file"
        return 0
    fi

    STAT_COREDUMP=$(echo "$dump_list" | wc -l)

    echo "# coredump backtrace" > "$output_path"
    echo "# Generated at $(date '+%Y-%m-%d %H:%M:%S')" >> "$output_path"

    # 构建 coredumpctl 前缀参数（是否带 --all）
    local coredumpctl_prefix="coredumpctl"
    if [ "$coredumpctl_supports_all" -eq 1 ]; then
        coredumpctl_prefix="coredumpctl --all"
    fi

    while IFS= read -r line; do
        [ -z "$line" ] && continue
        local pid
        pid=$(echo "$line" | awk '{print $5}')
        if [ -z "$pid" ]; then
            continue
        fi

        echo "" >> "$output_path"
        echo "===== PID: $pid =====" >> "$output_path"

        local gdb_ok=0

        if [ "$has_gdb" -eq 1 ]; then
            # 尝试用 gdb 获取 backtrace，带超时保护
            local gdb_ret=0
            if [ "$has_timeout" -eq 1 ]; then
                printf 'thread apply all bt\nquit\n' | timeout "$gdb_timeout" $coredumpctl_prefix gdb "$pid" >> "$output_path" 2>&1
                gdb_ret=$?
            else
                printf 'thread apply all bt\nquit\n' | $coredumpctl_prefix gdb "$pid" >> "$output_path" 2>&1
                gdb_ret=$?
            fi

            if [ "$gdb_ret" -eq 0 ]; then
                gdb_ok=1
            elif [ "$gdb_ret" -eq 124 ]; then
                log "gdb timed out for PID $pid (>${gdb_timeout}s), falling back to coredumpctl info"
            else
                log "gdb failed for PID $pid (exit code: $gdb_ret), falling back to coredumpctl info"
            fi
        fi

        # 回退逻辑：gdb 未安装 或 gdb 失败时，用 coredumpctl info 兜底
        if [ "$gdb_ok" -eq 0 ]; then
            echo "--- [fallback] coredumpctl info ---" >> "$output_path"
            if ! $coredumpctl_prefix info "$pid" >> "$output_path" 2>&1; then
                log "Failed to get coredump info for PID $pid (may require sudo)"
            fi
        fi

    done <<< "$dump_list"
}

save_command_output_to_file() {
    local command="$1"
    local output_dir="$2"
    local output_file="$3"

    create_directory "$output_dir"
    # 使用 bash -c 执行命令，避免 eval 带来的额外风险
    bash -c "$command" > "$output_dir/$output_file" 2>&1
    local ret=$?
    if [ $ret -ne 0 ]; then
        log "Failed to execute command: $command (exit code: $ret)"
        # 仅报错，不终止整个脚本
        return $ret
    fi
    STAT_CMD_SAVED=$((STAT_CMD_SAVED + 1))
    return 0
}

get_network_info_command() {
    if command -v ifconfig >/dev/null 2>&1; then
        echo "ifconfig"
    else
        echo "ip addr"
    fi
}

get_apt_repo_list_command() {
    local parallel="4"
    if command -v nproc >/dev/null 2>&1; then
        parallel=$(nproc)
        if [ -z "$parallel" ] || [ "$parallel" -lt 1 ]; then
            parallel="4"
        fi
    fi

    if command -v apt-cache >/dev/null 2>&1; then
        echo "apt-cache pkgnames | xargs -r -n 200 -P $parallel apt-cache madison"
    else
        echo "apt list --all-versions 2>/dev/null | tail -n +2 | cut -d/ -f1 | sort -u | xargs -r -n 200 -P $parallel apt-cache madison"
    fi
}

# ===== kconf2 配置采集（命令视图，与 /etc/kylin-config/ 配置文件互补）=====
# 注：以 SUDO_USER 身份执行 kconf2，确保读取的是软件商店实际运行用户的配置视图；
#     /etc/kylin-config/ 是磁盘上的真实配置文件，两者可对照分析。

# 以真实用户身份执行 kconf2（保留 HOME 与 XDG_RUNTIME_DIR 以兼容依赖会话的 kconf2 实现）
run_kconf2_as_user() {
    local target_uid=""
    target_uid=$(id -u "$REAL_USER" 2>/dev/null || echo "")
    if [ -n "$target_uid" ] && [ -d "/run/user/$target_uid" ]; then
        sudo -u "$REAL_USER" -H XDG_RUNTIME_DIR="/run/user/$target_uid" kconf2 "$@"
    else
        sudo -u "$REAL_USER" -H kconf2 "$@"
    fi
}

yaml_escape() {
    local value="$1"
    printf '%s' "$value" | sed ":a;N;\$!ba;s/\r//g;s/\n/\\\\n/g;s/'/''/g"
}

kconf2_is_error_output() {
    local output="$1"
    printf '%s\n' "$output" | grep -Eqi \
        'Wrong schema id|Get .*failed|list .*failed|failed to|get .* failed'
}

yaml_indent() {
    local indent="$1"
    printf '%*s' "$indent" ""
}

yaml_write_scalar() {
    local output_file="$1"
    local indent="$2"
    local key="$3"
    local value="$4"
    local spaces=""

    spaces=$(yaml_indent "$indent")
    printf "%s%s: '%s'\n" "$spaces" "$key" "$(yaml_escape "$value")" >> "$output_file"
}

yaml_write_list() {
    local output_file="$1"
    local indent="$2"
    local key="$3"
    local value="$4"
    local spaces=""
    local item_spaces=""
    local has_item=0

    spaces=$(yaml_indent "$indent")
    item_spaces=$(yaml_indent $((indent + 2)))

    if [ -z "$value" ]; then
        printf "%s%s: []\n" "$spaces" "$key" >> "$output_file"
        return 0
    fi

    printf "%s%s:\n" "$spaces" "$key" >> "$output_file"
    while IFS= read -r line || [ -n "$line" ]; do
        [ -z "$line" ] && continue
        has_item=1
        printf "%s- '%s'\n" "$item_spaces" "$(yaml_escape "$line")" >> "$output_file"
    done <<< "$value"

    if [ "$has_item" -eq 0 ]; then
        printf "%s- ''\n" "$item_spaces" >> "$output_file"
    fi
}

yaml_write_quoted_map_key() {
    local output_file="$1"
    local indent="$2"
    local key="$3"
    local spaces=""

    spaces=$(yaml_indent "$indent")
    printf "%s'%s':\n" "$spaces" "$(yaml_escape "$key")" >> "$output_file"
}

write_kconf2_failure_yaml() {
    local output_file="$1"
    local app_name="$2"
    local requested_version="$3"
    local status="$4"
    local error_message="$5"

    {
        echo "# Generated by kylin-software-center-saveLog"
        echo "schema_format: 'kconf2-yaml-v1'"
    } > "$output_file"
    yaml_write_scalar "$output_file" 0 "generated_at" "$(date '+%Y-%m-%d %H:%M:%S')"
    yaml_write_scalar "$output_file" 0 "app" "$app_name"
    yaml_write_scalar "$output_file" 0 "requested_version" "$requested_version"
    yaml_write_scalar "$output_file" 0 "selected_version" ""
    yaml_write_scalar "$output_file" 0 "status" "$status"
    yaml_write_scalar "$output_file" 0 "error" "$error_message"
}

write_kconf2_key_values() {
    local output_file="$1"
    local schema_ref="$2"
    local indent="$3"
    local keys_output=""
    local key=""
    local value_output=""
    local value_ret=0
    local keys_ret=0
    local spaces=""
    local has_key=0

    keys_output=$(run_kconf2_as_user list-keys "$schema_ref" 2>&1)
    keys_ret=$?

    if [ "$keys_ret" -ne 0 ] || kconf2_is_error_output "$keys_output"; then
        yaml_write_scalar "$output_file" "$indent" "status" "list_keys_failed"
        yaml_write_scalar "$output_file" "$indent" "error" "$keys_output"
        spaces=$(yaml_indent "$indent")
        printf "%skeys: {}\n" "$spaces" >> "$output_file"
        return 1
    fi

    yaml_write_scalar "$output_file" "$indent" "status" "ok"
    spaces=$(yaml_indent "$indent")
    printf "%skeys:\n" "$spaces" >> "$output_file"

    while IFS= read -r key || [ -n "$key" ]; do
        [ -z "$key" ] && continue
        has_key=1
        yaml_write_quoted_map_key "$output_file" $((indent + 2)) "$key"
        value_output=$(run_kconf2_as_user get "$schema_ref" "$key" 2>&1)
        value_ret=$?
        if [ "$value_ret" -eq 0 ] && ! kconf2_is_error_output "$value_output"; then
            yaml_write_scalar "$output_file" $((indent + 4)) "status" "ok"
            yaml_write_scalar "$output_file" $((indent + 4)) "value" "$value_output"
        else
            yaml_write_scalar "$output_file" $((indent + 4)) "status" "get_failed"
            yaml_write_scalar "$output_file" $((indent + 4)) "error" "$value_output"
        fi
    done <<< "$keys_output"

    if [ "$has_key" -eq 0 ]; then
        printf "%s  {}\n" "$spaces" >> "$output_file"
    fi

    return 0
}

collect_kconf2_app_config() {
    local app_name="$1"
    local requested_version="${2:-}"
    local output_dir="$ARCHIVE_DIR/kconf2"
    local safe_app_name="${app_name//\//_}"
    local output_file="$output_dir/${safe_app_name}.yaml"
    local apps_output=""
    local apps_ret=0
    local app_listed="unknown"
    local versions_output=""
    local versions_ret=0
    local versions_error=""
    local selected_version=""
    local schema_ref=""
    local children_output=""
    local children_ret=0
    local child=""
    local has_child=0

    create_directory "$output_dir"

    # 以 SUDO_USER 视角检测 kconf2 是否可用（与实际执行视角一致）
    if ! sudo -u "$REAL_USER" -H command -v kconf2 >/dev/null 2>&1; then
        write_kconf2_failure_yaml \
            "$output_file" \
            "$app_name" \
            "$requested_version" \
            "kconf2_not_found" \
            "kconf2 command not found"
        STAT_CMD_SAVED=$((STAT_CMD_SAVED + 1))
        log "kconf2 not found, wrote status file for $app_name"
        return 0
    fi

    apps_output=$(run_kconf2_as_user list-apps 2>&1)
    apps_ret=$?
    if [ "$apps_ret" -eq 0 ]; then
        if printf '%s\n' "$apps_output" | grep -Fxq "$app_name"; then
            app_listed="true"
        else
            app_listed="false"
        fi
    fi

    versions_output=$(run_kconf2_as_user list-versions "$app_name" 2>&1)
    versions_ret=$?
    if [ -n "$requested_version" ]; then
        selected_version="$requested_version"
    elif [ "$versions_ret" -eq 0 ] && \
        [ "$app_listed" != "false" ] && \
        ! kconf2_is_error_output "$versions_output"; then
        selected_version=$(printf '%s\n' "$versions_output" | sed '/^[[:space:]]*$/d' | sort -V | tail -n 1)
    fi

    if [ -z "$selected_version" ]; then
        versions_error="$versions_output"
        if [ -z "$versions_error" ] && [ "$app_listed" = "false" ]; then
            versions_error="app not found in kconf2 list-apps"
        fi
        write_kconf2_failure_yaml \
            "$output_file" \
            "$app_name" \
            "$requested_version" \
            "list_versions_failed" \
            "$versions_error"
        STAT_CMD_SAVED=$((STAT_CMD_SAVED + 1))
        log "Failed to determine kconf2 version for $app_name"
        return 0
    fi

    schema_ref="$app_name:$selected_version"

    {
        echo "# Generated by kylin-software-center-saveLog"
        echo "schema_format: 'kconf2-yaml-v1'"
    } > "$output_file"
    yaml_write_scalar "$output_file" 0 "generated_at" "$(date '+%Y-%m-%d %H:%M:%S')"
    yaml_write_scalar "$output_file" 0 "app" "$app_name"
    yaml_write_scalar "$output_file" 0 "requested_version" "$requested_version"
    yaml_write_scalar "$output_file" 0 "selected_version" "$selected_version"
    yaml_write_scalar "$output_file" 0 "schema" "$schema_ref"
    yaml_write_scalar "$output_file" 0 "status" "collected"

    printf "raw:\n" >> "$output_file"
    if [ "$apps_ret" -eq 0 ]; then
        yaml_write_list "$output_file" 2 "apps" "$apps_output"
    else
        yaml_write_scalar "$output_file" 2 "apps_status" "list_apps_failed"
        yaml_write_scalar "$output_file" 2 "apps_error" "$apps_output"
    fi
    if [ "$versions_ret" -eq 0 ]; then
        yaml_write_list "$output_file" 2 "versions" "$versions_output"
    else
        yaml_write_scalar "$output_file" 2 "versions_status" "list_versions_failed"
        yaml_write_scalar "$output_file" 2 "versions_error" "$versions_output"
    fi

    printf "root:\n" >> "$output_file"
    yaml_write_scalar "$output_file" 2 "schema" "$schema_ref"
    write_kconf2_key_values "$output_file" "$schema_ref" 2 || true

    children_output=$(run_kconf2_as_user list-children "$schema_ref" 2>&1)
    children_ret=$?
    printf "children:\n" >> "$output_file"
    if printf '%s\n' "$children_output" | grep -qi "No child"; then
        yaml_write_scalar "$output_file" 2 "status" "no_child"
        yaml_write_scalar "$output_file" 2 "message" "$children_output"
    elif [ "$children_ret" -ne 0 ] || kconf2_is_error_output "$children_output"; then
        yaml_write_scalar "$output_file" 2 "status" "list_children_failed"
        yaml_write_scalar "$output_file" 2 "error" "$children_output"
    else
        yaml_write_scalar "$output_file" 2 "status" "ok"
        printf "  items:\n" >> "$output_file"
        while IFS= read -r child || [ -n "$child" ]; do
            [ -z "$child" ] && continue
            has_child=1
            yaml_write_quoted_map_key "$output_file" 4 "$child"
            yaml_write_scalar "$output_file" 6 "schema" "$child:$selected_version"
            write_kconf2_key_values "$output_file" "$child:$selected_version" 6 || true
        done <<< "$children_output"

        if [ "$has_child" -eq 0 ]; then
            printf "    {}\n" >> "$output_file"
        fi
    fi

    STAT_CMD_SAVED=$((STAT_CMD_SAVED + 1))
    log "Collected kconf2 config for $app_name to kconf2/${safe_app_name}.yaml"
}

collect_kconf2_configs() {
    collect_kconf2_app_config "kylin-software-center" ""
}

# 获取收集级别的中文名称
get_level_label() {
    case "$COLLECT_LEVEL" in
        basic)    echo "基础（默认）" ;;
        standard) echo "标准" ;;
        full)     echo "完整" ;;
    esac
}

# 打印启动时的收集摘要
print_collect_summary() {
    local yes="✓"
    local no="✗"

    echo ""
    echo "==============================================="
    echo "  软件商店日志收集工具 v$SCRIPT_VERSION"
    echo "  当前收集级别: $(get_level_label)"
    echo "  目标用户家目录: $HOME_DIR (来自 sudo 调用者 $REAL_USER)"
    echo "==============================================="
    echo "  [$yes] 软件商店日志与用户缓存 ($HOME_DIR/.cache/uksc/)"
    echo "  [$yes] 系统版本与环境信息"
    echo "  [$yes] apt/dpkg 状态与操作日志"
    echo "  [$yes] coredump 调用栈 (backtrace)"
    echo "  [$yes] 软件环境信息 (dpkg/kare/kaiming)"
    echo "  [$yes] syslog (完整收集)"
    echo "  [$yes] syslog.1 (logrotate 归档)"
    echo "  [$yes] /etc/kylin-config/ 配置目录"
    echo "  [$yes] kconf2 配置 (YAML, 如可用)"

    if [ "$INCLUDE_APT_DIR" -eq 1 ]; then
        echo "  [$yes] /var/lib/apt/ 目录"
    else
        echo "  [$no] /var/lib/apt/ 目录            (--level standard 开启)"
    fi

    if [ "$INCLUDE_COREDUMP" -eq 1 ]; then
        echo "  [$yes] coredump 原始文件"
    else
        echo "  [$no] coredump 原始文件           (--level standard 开启)"
    fi

    if [ "$INCLUDE_ICON_DIRS" -eq 1 ]; then
        echo "  [$yes] 图标/广告/图片缓存"
    else
        echo "  [$no] 图标/广告/图片缓存          (--level standard 开启)"
    fi

    if [ "$INCLUDE_DEB" -eq 1 ]; then
        echo "  [$yes] 下载的 deb 安装包"
    else
        echo "  [$no] 下载的 deb 安装包          (--level full 开启)"
    fi

    if [ "$INCLUDE_APT_REPO_LIST" -eq 1 ]; then
        echo "  [$yes] apt 完整仓库列表 (耗时较长)"
    else
        echo "  [$no] apt 完整仓库列表 (耗时较长)  (--level full 开启)"
    fi

    echo "==============================================="
    echo ""
}

# dry-run 模式：展示将收集的路径及其状态，不实际执行
run_dry_run() {
    print_collect_summary

    echo "[预览模式] 以下为本次将收集的路径，不会实际执行:"
    echo ""

    for LOG_FILE in "${LOG_FILES[@]}"; do
        if [ -e "$LOG_FILE" ]; then
            local size=""
            if [ -f "$LOG_FILE" ]; then
                size=$(du -sh "$LOG_FILE" 2>/dev/null | awk '{print $1}')
                echo "  ✓ $LOG_FILE  ($size)"
            elif [ -d "$LOG_FILE" ]; then
                # 构建 du --exclude 参数，与 rsync 排除保持一致
                local du_excludes=()
                for skip in "${SKIP_DIRS[@]}"; do
                    # 如果 skip 是当前目录的子目录，则排除
                    local normalized_log="${LOG_FILE%/}/"
                    local normalized_skip="${skip%/}/"
                    if [[ "$normalized_skip" == "$normalized_log"* ]]; then
                        du_excludes+=(--exclude="${normalized_skip}")
                    fi
                done
                size=$(du -sh "${du_excludes[@]}" "$LOG_FILE" 2>/dev/null | tail -1 | awk '{print $1}')
                if [ ${#du_excludes[@]} -gt 0 ]; then
                    echo "  ✓ $LOG_FILE  (目录, $size, 已排除 ${#du_excludes[@]} 个子目录)"
                else
                    echo "  ✓ $LOG_FILE  (目录, $size)"
                fi
            fi
        else
            echo "  ✗ $LOG_FILE  (不存在, 将跳过)"
        fi
    done

    echo ""

    # 检查 ~/.log/ 下的匹配文件
    local user_log_count=0
    if [ -d "$HOME_DIR/.log/" ]; then
        user_log_count=$(find "$HOME_DIR/.log/" -type f \( -name "*kylin-software-center*" -o -name "*kylin-id*" \) 2>/dev/null | wc -l)
    fi
    echo "  $HOME_DIR/.log/ 下匹配的用户日志文件: $user_log_count 个"

    # 检查 coredump 状态
    if command -v coredumpctl >/dev/null 2>&1; then
        local coredump_count
        coredump_count=$(coredumpctl list --no-legend 2>/dev/null | grep -cE "software-center|kylin-software" || echo "0")
        echo "  coredump 匹配记录: $coredump_count 条"
    else
        echo "  coredumpctl 未安装, 将跳过 coredump 收集"
    fi

    if sudo -u "$REAL_USER" -H command -v kconf2 >/dev/null 2>&1; then
        echo "  kconf2 配置: 将以 $REAL_USER 身份采集 kylin-software-center"
    else
        echo "  kconf2 配置: $REAL_USER 视角下未安装, 将写入状态文件"
    fi

    if [ "$INCLUDE_COREDUMP" -eq 1 ]; then
        local core_count=0
        if [ -d "/var/lib/systemd/coredump/" ]; then
            core_count=$(find /var/lib/systemd/coredump/ -name "*kylin-software*" 2>/dev/null | wc -l)
        fi
        echo "  coredump 原始文件: $core_count 个"
    fi

    echo ""
    echo "如需跳过的目录:"
    for skip in "${SKIP_DIRS[@]}"; do
        echo "  ✗ $skip"
    done

    echo ""
    echo "确认无误后，去掉 --dry-run 参数即可正式收集。"
    exit 0
}

# 打印收集结束的结果摘要
print_result_summary() {
    local archive_size=""
    if [ -f "$ARCHIVE_FILE" ]; then
        archive_size=$(du -sh "$ARCHIVE_FILE" 2>/dev/null | awk '{print $1}')
    fi

    echo ""
    echo "==============================================="
    echo "  收集完成 (脚本版本: v$SCRIPT_VERSION)"
    echo "-----------------------------------------------"
    echo "  rsync 复制路径:  $STAT_COPIED"
    echo "  命令输出文件:    $STAT_CMD_SAVED"
    echo "  跳过(不存在):    $STAT_SKIPPED 个路径"
    echo "  coredump:        ${STAT_COREDUMP} 条匹配记录"
    echo "  压缩包大小:      ${archive_size:-未知}"
    echo "  压缩包路径:      $ARCHIVE_FILE"

    # 检查是否已复制到桌面
    if [ -n "${DESKTOP_COPY_STATUS:-}" ]; then
        echo "  桌面副本:      $DESKTOP_COPY_STATUS"
    fi

    echo "==============================================="
    echo ""
}

# 打印磁盘空间信息（/tmp 和 /）
print_disk_space() {
    local label="$1"
    local tmp_avail root_avail
    tmp_avail=$(df -h --output=avail /tmp 2>/dev/null | tail -1 | tr -d ' ')
    root_avail=$(df -h --output=avail / 2>/dev/null | tail -1 | tr -d ' ')
    log "${label} - /tmp 可用: ${tmp_avail:-未知}, / 可用: ${root_avail:-未知}"
}

# 主函数
save_kylin_software_center_log() {
    # 打印启动摘要
    print_collect_summary

    log "Starting log collection (level: $COLLECT_LEVEL, script: v$SCRIPT_VERSION)"
    create_directory "$ARCHIVE_DIR"

    # 写入收集脚本版本号，方便研发确认客户使用的脚本版本
    echo "$SCRIPT_VERSION" > "$ARCHIVE_DIR/collector_version.txt"

    # 收集 kconf2 配置，若 kconf2 不存在也写入状态文件
    collect_kconf2_configs

    # 打印收集前的磁盘空间
    print_disk_space "收集前磁盘空间"

    # 前置检查: standard/full 级别下 /tmp 可用空间不足 1G 时跳过额外收集
    local tmp_avail_kb
    tmp_avail_kb=$(df --output=avail /tmp 2>/dev/null | tail -1 | tr -d ' ')
    if [ -n "$tmp_avail_kb" ] 2>/dev/null; then
        if [ "$tmp_avail_kb" -lt 1048576 ] && [ "$COLLECT_LEVEL" != "basic" ]; then
            local tmp_avail_mb=$((tmp_avail_kb / 1024))
            log "警告: /tmp 可用空间仅 ${tmp_avail_mb}MB (<1GB)，当前级别为 $(get_level_label)，降级为 basic 仅收集基础信息"
            # 降级：关闭所有额外收集开关
            INCLUDE_APT_DIR=0
            INCLUDE_COREDUMP=0
            INCLUDE_ICON_DIRS=0
            INCLUDE_DEB=0
            INCLUDE_APT_REPO_LIST=0
        elif [ "$tmp_avail_kb" -lt 204800 ]; then
            local tmp_avail_mb=$((tmp_avail_kb / 1024))
            log "警告: /tmp 可用空间仅 ${tmp_avail_mb}MB (<200MB)，收集过程中可能空间不足"
        fi
    fi

    # 仅收集 ~/.log/ 下文件名包含 kylin-software-center 或 kylin-id 的文件
    add_files_with_string_to_log_files "$HOME_DIR/.log/" "kylin-software-center"
    add_files_with_string_to_log_files "$HOME_DIR/.log/" "kylin-id"

    # 收集 coredump 调用栈信息（backtrace）
    collect_coredump_backtraces "$ARCHIVE_DIR"

    # 仅在开启参数时收集 coredump 原始文件（默认不开启）
    if [ "$INCLUDE_COREDUMP" -eq 1 ]; then
        add_files_with_string_to_log_files "/var/lib/systemd/coredump/" "kylin-software"
    fi

    # 忽略命令失败，继续执行后续步骤
    save_command_output_to_file "dpkg -l" "$ARCHIVE_DIR" "dpkg-version.log" || true
    save_command_output_to_file "kare -l" "$ARCHIVE_DIR" "kare-version.log" || true
    save_command_output_to_file "kaiming list" "$ARCHIVE_DIR" "kaiming-version.log" || true
    save_command_output_to_file "cat /proc/cpuinfo" "$ARCHIVE_DIR" "cpuinfo.log" || true
    save_command_output_to_file "$(get_network_info_command)" "$ARCHIVE_DIR" "ifconfig.log" || true
    save_command_output_to_file "apt list --all-versions" "$ARCHIVE_DIR" "apt_all_versions.log" || true
    save_command_output_to_file "kaiming search" "$ARCHIVE_DIR" "kaiming_search.log" || true

    if [ "$INCLUDE_APT_REPO_LIST" -eq 1 ]; then
        save_command_output_to_file "$(get_apt_repo_list_command)" "$ARCHIVE_DIR" "apt_all_versions_with_repo.txt" || true
    fi

    copy_log_files

    # 打印收集后的磁盘空间
    print_disk_space "收集后磁盘空间"

    archive_logs
    copy_archive_to_desktop
    cleanup

    # 打印结果摘要
    print_result_summary
    log "Logs have been archived to $ARCHIVE_FILE"
}

# 解析参数并应用选项
parse_args "$@"
apply_extra_options

# dry-run 模式：仅预览，不实际执行
if [ "$DRY_RUN" -eq 1 ]; then
    # dry-run 也需要补充 ~/.log/ 下的文件到 LOG_FILES 用于展示
    add_files_with_string_to_log_files "$HOME_DIR/.log/" "kylin-software-center"
    add_files_with_string_to_log_files "$HOME_DIR/.log/" "kylin-id"
    run_dry_run
fi

# 调用主函数
save_kylin_software_center_log