#!/bin/bash

# 定义日志文件路径
LOG_FILES=(
    "$HOME/.log/"
    "$HOME/.cache/uksc/"
    "/var/log/kylin-system-updater/"
    "/var/log/syslog"
    "/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"
)

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

# ===== 额外参数（默认不开启）=====
INCLUDE_DEB=0
INCLUDE_COREDUMP=0
INCLUDE_ICON_DIRS=0

print_usage() {
    cat <<EOF
Usage: $0 [options]

Options (disabled by default):
  --include-deb         Include downloaded deb packages: ~/.cache/uksc/wget_down/
  --include-coredump    Include coredump files by scanning /var/lib/systemd/coredump/ with name contains "kylin-software"
  --include-icons       Include icon/ad/image cache dirs:
                        ~/.cache/uksc/icons/
                        ~/.cache/uksc/ads/
                        ~/.cache/uksc/coverimage/
                        ~/.cache/uksc/imagecode/
                        ~/.cache/uksc/previewImage/
  -h, --help            Show this help

Examples:
  $0
  $0 --include-deb
  $0 --include-icons --include-coredump
EOF
}

parse_args() {
    while [ $# -gt 0 ]; do
        case "$1" in
            --include-deb)
                INCLUDE_DEB=1
                shift
                ;;
            --include-coredump)
                INCLUDE_COREDUMP=1
                shift
                ;;
            --include-icons)
                INCLUDE_ICON_DIRS=1
                shift
                ;;
            -h|--help)
                print_usage
                exit 0
                ;;
            *)
                echo "Unknown option: $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() {
    # 需要收集 deb 包：从 SKIP_DIRS 中移除 wget_down
    if [ "$INCLUDE_DEB" -eq 1 ]; then
        remove_skip_dir "$HOME/.cache/uksc/wget_down/"
    fi

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

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

# 创建临时日志存储文件夹
ARCHIVE_DIR="/tmp/kylin-software-center-log_archive_$TIMESTAMP"
ARCHIVE_FILE="/tmp/kylin-software-center-logs_$TIMESTAMP.tar.gz"

# 日志函数
log() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message"
}

# 检查并创建目录
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 参数（只构建一次，避免循环内重复构建）
    EXCLUDE_ARGS=()
    for skip in "${SKIP_DIRS[@]}"; do
        EXCLUDE_ARGS+=(--exclude="${skip}")
    done

    for LOG_FILE in "${LOG_FILES[@]}"; do
        if [ -e "$LOG_FILE" ]; then
            rsync -aRL "${EXCLUDE_ARGS[@]}" "$LOG_FILE" "$ARCHIVE_DIR" 2>/dev/null
            if [ $? -ne 0 ]; then
                log "Failed to copy log file or directory: $LOG_FILE"
            fi
        else
            log "Log file or directory does not exist: $LOG_FILE"
        fi
    done
}

# 打包日志文件
archive_logs() {
    tar -czvf "$ARCHIVE_FILE" -C "$ARCHIVE_DIR" .
    if [ $? -ne 0 ]; then
        log "Failed to create archive: $ARCHIVE_FILE"
        exit 1
    fi
}

# 将归档文件拷贝一份到桌面
copy_archive_to_desktop() {
    local desktop_dir=""
    if command -v xdg-user-dir >/dev/null 2>&1; then
        desktop_dir=$(xdg-user-dir DESKTOP 2>/dev/null || true)
    fi
    if [ -z "$desktop_dir" ] || [ ! -d "$desktop_dir" ]; then
        if [ -d "$HOME/Desktop" ]; then
            desktop_dir="$HOME/Desktop"
        elif [ -d "$HOME/桌面" ]; then
            desktop_dir="$HOME/桌面"
        else
            desktop_dir=""
        fi
    fi

    if [ -n "$desktop_dir" ]; then
        cp -f "$ARCHIVE_FILE" "$desktop_dir/" && log "Archive copied to Desktop: $desktop_dir"
    else
        log "Desktop directory not found"
    fi
}

# 清理临时目录
cleanup() {
    rm -rf "$ARCHIVE_DIR"
    if [ $? -ne 0 ]; then
        log "Failed to clean up directory: $ARCHIVE_DIR"
        exit 1
    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" -type f -name "*$search_str*" -print0)
    else
        log "Directory does not exist: $dir"
    fi
}

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
    return 0
}

# 主函数
save_kylin_installer_log() {
    log "Starting log collection"
    create_directory "$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

    copy_log_files
    archive_logs
    copy_archive_to_desktop
    cleanup
    log "Logs have been archived to $ARCHIVE_FILE"
}

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

# 调用主函数
save_kylin_installer_log