#!/system/bin/sh
# KernelSU模块配置管理工具
# 用于管理全局、模块特定和WebUI配置

# 导入通用函数库
. /usr/lib/common-functions.sh

# 配置文件路径
readonly GLOBAL_CONFIG="/usr/etc/kernelsu-global.conf"
readonly USER_CONFIG="$HOME/.kernelsu.conf"
readonly MODULE_CONFIG_DIR="/data/adb/modules_config"
readonly WEBUI_CONFIG_DIR="/data/adb/webui_config"

# 显示帮助信息
show_help() {
    cat << 'EOF'
KernelSU配置管理工具

用法:
    config-manager [选项] [操作] [参数...]

选项:
    -h, --help          显示帮助信息
    -v, --version       显示版本信息
    -q, --quiet         安静模式
    -d, --debug         调试模式
    --global            操作全局配置
    --user              操作用户配置
    --module MODULE_ID  操作模块配置
    --webui             操作WebUI配置

操作:
    list                列出所有配置项
    get KEY             获取配置值
    set KEY VALUE       设置配置值
    unset KEY           删除配置项
    reset               重置配置为默认值
    backup PATH         备份配置到文件
    restore PATH        从文件恢复配置
    validate            验证配置有效性
    merge SOURCE        合并配置文件

示例:
    config-manager --global list
    config-manager --global set log_level debug
    config-manager --module my_module get enable_webui
    config-manager --webui set default_port 8080
    config-manager backup /sdcard/kernelsu_config.backup
    config-manager validate

EOF
}

# 显示版本信息
show_version() {
    echo "KernelSU配置管理工具 v1.0.0"
    echo "Copyright (C) 2024 RootManage-Module-Model Project"
}

# 获取配置文件路径
get_config_file() {
    local scope="$1"
    local module_id="$2"
    
    case "$scope" in
        "global")
            echo "$GLOBAL_CONFIG"
            ;;
        "user")
            echo "$USER_CONFIG"
            ;;
        "module")
            if [ -z "$module_id" ]; then
                log_error "模块ID不能为空"
                return 1
            fi
            echo "$MODULE_CONFIG_DIR/$module_id.conf"
            ;;
        "webui")
            echo "$WEBUI_CONFIG_DIR/webui.conf"
            ;;
        *)
            log_error "无效的配置范围: $scope"
            return 1
            ;;
    esac
}

# 确保配置文件存在
ensure_config_file() {
    local config_file="$1"
    local config_dir=$(dirname "$config_file")
    
    # 创建配置目录
    if [ ! -d "$config_dir" ]; then
        mkdir -p "$config_dir"
        chmod 755 "$config_dir"
    fi
    
    # 创建配置文件
    if [ ! -f "$config_file" ]; then
        touch "$config_file"
        chmod 644 "$config_file"
        log_debug "创建配置文件: $config_file"
    fi
}

# 列出配置项
list_config() {
    local config_file="$1"
    
    if [ ! -f "$config_file" ]; then
        log_warn "配置文件不存在: $config_file"
        return 1
    fi
    
    log_info "配置文件: $config_file"
    echo "配置项:"
    
    while IFS='=' read -r key value; do
        # 跳过注释和空行
        [ -z "$key" ] && continue
        [ "${key#\#}" != "$key" ] && continue
        
        printf "  %-30s = %s\n" "$key" "$value"
    done < "$config_file"
}

# 获取配置值
get_config() {
    local config_file="$1"
    local key="$2"
    
    if [ ! -f "$config_file" ]; then
        log_debug "配置文件不存在: $config_file"
        return 1
    fi
    
    local value=$(grep "^$key=" "$config_file" | cut -d'=' -f2- | head -1)
    if [ -n "$value" ]; then
        echo "$value"
        return 0
    else
        return 1
    fi
}

# 设置配置值
set_config() {
    local config_file="$1"
    local key="$2"
    local value="$3"
    
    ensure_config_file "$config_file"
    
    # 检查是否已存在
    if grep -q "^$key=" "$config_file"; then
        # 更新现有配置
        sed -i "s|^$key=.*|$key=$value|" "$config_file"
        log_info "更新配置: $key = $value"
    else
        # 添加新配置
        echo "$key=$value" >> "$config_file"
        log_info "添加配置: $key = $value"
    fi
}

# 删除配置项
unset_config() {
    local config_file="$1"
    local key="$2"
    
    if [ ! -f "$config_file" ]; then
        log_warn "配置文件不存在: $config_file"
        return 1
    fi
    
    if grep -q "^$key=" "$config_file"; then
        sed -i "/^$key=/d" "$config_file"
        log_info "删除配置: $key"
        return 0
    else
        log_warn "配置项不存在: $key"
        return 1
    fi
}

# 重置配置为默认值
reset_config() {
    local config_file="$1"
    local scope="$2"
    
    log_info "重置配置: $config_file"
    
    # 备份现有配置
    if [ -f "$config_file" ]; then
        local backup_file="$config_file.backup.$(date +%Y%m%d_%H%M%S)"
        cp "$config_file" "$backup_file"
        log_info "备份现有配置: $backup_file"
    fi
    
    # 生成默认配置
    case "$scope" in
        "global")
            generate_default_global_config "$config_file"
            ;;
        "user")
            generate_default_user_config "$config_file"
            ;;
        "webui")
            generate_default_webui_config "$config_file"
            ;;
        *)
            log_warn "不支持重置此类型的配置: $scope"
            return 1
            ;;
    esac
    
    log_info "配置重置完成"
}

# 生成默认全局配置
generate_default_global_config() {
    local config_file="$1"
    
    cat > "$config_file" << 'EOF'
# KernelSU全局配置文件
# Global configuration for KernelSU

# 日志设置
log_level=info
log_file=/data/adb/kernelsu.log
log_max_size=10MB
log_rotate_count=5

# 模块设置
module_auto_mount=true
module_check_integrity=true
module_enable_cache=true
module_backup_on_update=true

# WebUI设置
webui_enabled=false
webui_default_port=8080
webui_auto_start=false
webui_auth_required=true

# 安全设置
enforce_signature=false
allow_untrusted_modules=true
enable_selinux_patch=true
enable_bootloop_protection=true

# 性能设置
parallel_module_loading=true
cache_module_info=true
optimize_mount_points=true

# 兼容性设置
magisk_compatibility_mode=true
detect_other_root=true
hide_from_detection=true

# 更新设置
check_updates_automatically=false
update_check_interval=86400
download_updates_wifi_only=true

EOF
}

# 生成默认用户配置
generate_default_user_config() {
    local config_file="$1"
    
    cat > "$config_file" << 'EOF'
# KernelSU用户配置文件
# User configuration for KernelSU

# 个人偏好
preferred_editor=vi
preferred_shell=/system/bin/sh
show_notifications=true
use_color_output=true

# 开发设置
enable_debug_mode=false
enable_verbose_logging=false
auto_backup_modules=true
validate_modules_on_install=true

# WebUI偏好
webui_theme=default
webui_language=auto
webui_show_advanced_options=false

# 工具设置
auto_check_dependencies=true
prompt_before_dangerous_operations=true
use_parallel_operations=true

EOF
}

# 生成默认WebUI配置
generate_default_webui_config() {
    local config_file="$1"
    
    cat > "$config_file" << 'EOF'
# KernelSU WebUI配置文件
# WebUI configuration for KernelSU

# 服务器设置
server_type=python
bind_address=127.0.0.1
port=8080
ssl_enabled=false
ssl_cert_file=
ssl_key_file=

# 认证设置
auth_enabled=true
session_timeout=3600
max_login_attempts=5
lockout_duration=300

# 界面设置
theme=default
language=auto
items_per_page=20
show_system_info=true
show_performance_metrics=true

# 功能设置
allow_module_install=true
allow_module_uninstall=true
allow_system_reboot=true
allow_config_edit=true
allow_log_view=true

# 安全设置
csrf_protection=true
xss_protection=true
content_security_policy=strict
allowed_origins=*

EOF
}

# 备份配置
backup_config() {
    local backup_file="$1"
    local temp_dir="/tmp/config_backup_$$"
    
    log_info "备份配置到: $backup_file"
    
    # 创建临时目录
    mkdir -p "$temp_dir"
    
    # 复制配置文件
    [ -f "$GLOBAL_CONFIG" ] && cp "$GLOBAL_CONFIG" "$temp_dir/global.conf"
    [ -f "$USER_CONFIG" ] && cp "$USER_CONFIG" "$temp_dir/user.conf"
    
    # 复制模块配置
    if [ -d "$MODULE_CONFIG_DIR" ]; then
        mkdir -p "$temp_dir/modules"
        cp "$MODULE_CONFIG_DIR"/*.conf "$temp_dir/modules/" 2>/dev/null || true
    fi
    
    # 复制WebUI配置
    if [ -d "$WEBUI_CONFIG_DIR" ]; then
        mkdir -p "$temp_dir/webui"
        cp "$WEBUI_CONFIG_DIR"/*.conf "$temp_dir/webui/" 2>/dev/null || true
    fi
    
    # 创建备份档案
    if tar -czf "$backup_file" -C "$temp_dir" .; then
        log_info "配置备份成功: $backup_file"
        rm -rf "$temp_dir"
        return 0
    else
        log_error "配置备份失败"
        rm -rf "$temp_dir"
        return 1
    fi
}

# 恢复配置
restore_config() {
    local backup_file="$1"
    local temp_dir="/tmp/config_restore_$$"
    
    if [ ! -f "$backup_file" ]; then
        log_error "备份文件不存在: $backup_file"
        return 1
    fi
    
    log_info "从备份恢复配置: $backup_file"
    
    # 创建临时目录
    mkdir -p "$temp_dir"
    
    # 解压备份档案
    if ! tar -xzf "$backup_file" -C "$temp_dir"; then
        log_error "解压备份文件失败"
        rm -rf "$temp_dir"
        return 1
    fi
    
    # 恢复全局配置
    if [ -f "$temp_dir/global.conf" ]; then
        ensure_config_file "$GLOBAL_CONFIG"
        cp "$temp_dir/global.conf" "$GLOBAL_CONFIG"
        log_info "恢复全局配置"
    fi
    
    # 恢复用户配置
    if [ -f "$temp_dir/user.conf" ]; then
        ensure_config_file "$USER_CONFIG"
        cp "$temp_dir/user.conf" "$USER_CONFIG"
        log_info "恢复用户配置"
    fi
    
    # 恢复模块配置
    if [ -d "$temp_dir/modules" ]; then
        mkdir -p "$MODULE_CONFIG_DIR"
        cp "$temp_dir/modules"/*.conf "$MODULE_CONFIG_DIR/" 2>/dev/null || true
        log_info "恢复模块配置"
    fi
    
    # 恢复WebUI配置
    if [ -d "$temp_dir/webui" ]; then
        mkdir -p "$WEBUI_CONFIG_DIR"
        cp "$temp_dir/webui"/*.conf "$WEBUI_CONFIG_DIR/" 2>/dev/null || true
        log_info "恢复WebUI配置"
    fi
    
    # 清理临时文件
    rm -rf "$temp_dir"
    
    log_info "配置恢复完成"
    return 0
}

# 验证配置有效性
validate_config() {
    local config_file="$1"
    local errors=0
    
    if [ ! -f "$config_file" ]; then
        log_error "配置文件不存在: $config_file"
        return 1
    fi
    
    log_info "验证配置文件: $config_file"
    
    # 检查语法错误
    while IFS= read -r line; do
        # 跳过注释和空行
        [ -z "$line" ] && continue
        [ "${line#\#}" != "$line" ] && continue
        
        # 检查格式
        if ! echo "$line" | grep -q "^[a-zA-Z_][a-zA-Z0-9_]*="; then
            log_error "配置格式错误: $line"
            errors=$((errors + 1))
        fi
    done < "$config_file"
    
    if [ $errors -eq 0 ]; then
        log_info "配置验证通过"
        return 0
    else
        log_error "发现 $errors 个配置错误"
        return 1
    fi
}

# 合并配置文件
merge_config() {
    local source_file="$1"
    local target_file="$2"
    
    if [ ! -f "$source_file" ]; then
        log_error "源配置文件不存在: $source_file"
        return 1
    fi
    
    ensure_config_file "$target_file"
    
    log_info "合并配置: $source_file -> $target_file"
    
    # 读取源文件并合并
    while IFS='=' read -r key value; do
        # 跳过注释和空行
        [ -z "$key" ] && continue
        [ "${key#\#}" != "$key" ] && continue
        
        # 设置配置
        set_config "$target_file" "$key" "$value"
    done < "$source_file"
    
    log_info "配置合并完成"
}

# 主函数
main() {
    local scope="global"
    local module_id=""
    local operation=""
    local key=""
    local value=""
    local file_path=""
    
    # 解析参数
    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)
                show_help
                exit 0
                ;;
            -v|--version)
                show_version
                exit 0
                ;;
            -q|--quiet)
                QUIET=true
                ;;
            -d|--debug)
                DEBUG=true
                ;;
            --global)
                scope="global"
                ;;
            --user)
                scope="user"
                ;;
            --module)
                scope="module"
                module_id="$2"
                shift
                ;;
            --webui)
                scope="webui"
                ;;
            list|get|set|unset|reset|backup|restore|validate|merge)
                operation="$1"
                ;;
            *)
                if [ -z "$key" ]; then
                    key="$1"
                elif [ -z "$value" ]; then
                    value="$1"
                elif [ -z "$file_path" ]; then
                    file_path="$1"
                fi
                ;;
        esac
        shift
    done
    
    # 获取配置文件路径
    local config_file
    if ! config_file=$(get_config_file "$scope" "$module_id"); then
        exit 1
    fi
    
    # 执行操作
    case "$operation" in
        list)
            list_config "$config_file"
            ;;
        get)
            if [ -z "$key" ]; then
                log_error "请指定配置键名"
                exit 1
            fi
            if get_config "$config_file" "$key"; then
                exit 0
            else
                exit 1
            fi
            ;;
        set)
            if [ -z "$key" ] || [ -z "$value" ]; then
                log_error "请指定配置键名和值"
                exit 1
            fi
            set_config "$config_file" "$key" "$value"
            ;;
        unset)
            if [ -z "$key" ]; then
                log_error "请指定配置键名"
                exit 1
            fi
            unset_config "$config_file" "$key"
            ;;
        reset)
            reset_config "$config_file" "$scope"
            ;;
        backup)
            if [ -z "$key" ]; then
                log_error "请指定备份文件路径"
                exit 1
            fi
            backup_config "$key"
            ;;
        restore)
            if [ -z "$key" ]; then
                log_error "请指定备份文件路径"
                exit 1
            fi
            restore_config "$key"
            ;;
        validate)
            validate_config "$config_file"
            ;;
        merge)
            if [ -z "$key" ]; then
                log_error "请指定源配置文件路径"
                exit 1
            fi
            merge_config "$key" "$config_file"
            ;;
        "")
            log_error "请指定操作"
            show_help
            exit 1
            ;;
        *)
            log_error "无效的操作: $operation"
            exit 1
            ;;
    esac
}

# 检查参数并运行主函数
if [ $# -eq 0 ]; then
    show_help
    exit 0
fi

main "$@"
