#!/bin/bash

# 根据调用名称确定使用哪个原始命令
SCRIPT_NAME=$(basename "$0")
if [ "$SCRIPT_NAME" = "apt-get" ]; then
    ORIGINAL_CMD="/usr/bin/apt-get.orig"
elif [ "$SCRIPT_NAME" = "apt" ]; then
    ORIGINAL_CMD="/usr/bin/apt.orig"
else
    ORIGINAL_CMD="/usr/bin/apt.orig"  # 默认使用apt.orig
fi

WRAPPER_TAG="apt_wrapper"

func_lib_path="/usr/bin/wrapper_common"
if [ -f "$func_lib_path" ]; then
    source "$func_lib_path"
fi

apt_cache_dir="/tmp/kysdk-package/apt-cache"

parse_apt_args() {
    local -n __packages=$1
    local -n __options=$2
    shift 2
    
    __packages=()
    __options=()
    
    while [ $# -gt 0 ]; do
        case "$1" in
            -o|--option|-c|--config-file)
                __options+=("$1")
                shift
                # 检查下一个参数是否存在且不是选项
                if [ $# -gt 0 ] && [[ ! "$1" =~ ^- ]]; then
                    __options+=("$1")
                    shift
                else
                    log "警告: 选项 $1 需要参数"
                fi
                ;;
            
            -*)
                __options+=("$1")
                shift
                ;;
            
            *)
                __packages+=("$1")
                shift
                ;;
        esac
    done
}


# 专门处理带选项的卸载操作
handle_remove_with_options() {
    local operation=$1
    shift
    local options=()
    local packages=()
    
    parse_apt_args packages options "$@"
    options+=("-y")
    log "处理带选项的卸载: options=[${options[*]}], packages=[${packages[*]}]"

    #如果包是空的直接general处理
    if [ ${#packages[@]} -eq 0 ] ; then
        log "kypackage_general传入参数: ${options[*]}"
        /usr/bin/kypackage_general apt.orig "${operation}" "${options[@]}"
        return 0
    fi
    #is a non-privileged package and cannot be uninstalled
    for package_name in "${packages[@]}"; do
        pkg_env=$(pkg_in_sys $package_name "env")
        pkg_status=$?
        if [ $pkg_status -ne 0 ];then
            printf "软件包 ${package_name} 未安装，所以不会被卸载\n"
        else
            # 检查包是否存在，如果存在则执行kare -P
            if [[ $pkg_env = "kare_"* ]]; then
                log "检测到kare环境包 ${package_name}，环境为 ${pkg_env}"
                /usr/bin/kypackage_remove "${package_name}"
            # kconf2读取的包列表带单引号，比较时也应添加单引号
            elif ! is_in_white_list ${package_name} && ! is_in_privilege_list \'${package_name}\' && pkg_is_in_ostree ${package_name}; then
                printf "当前模式下,软件包 ${package_name} 不允许卸载\n"
            else
                log "检测到可卸载软件包 ${package_name}, 使用原生apt"
                /usr/bin/kypackage_desktop  "--remove" $package_name
                /usr/bin/kypackage_general apt.orig "${operation}" "${options[@]}" "${package_name}"
                local search_result=$(dpkg -l | grep "^ii[[:space:]]\+${package_name}[[:space:]]" 2>/dev/null)
                if [ -z "$search_result" ]; then
                    printf "卸载成功，软件包已从核心系统中移除\n"
                fi
            fi
        fi
    done
    return 0
}

# 运维模式卸载操作
handle_remove_in_maintain_mode() {
    local operation=$1
    shift
    local options=()
    local packages=()
    
    parse_apt_args packages options "$@"
    options+=("-y")
    log "处理带选项的卸载: options=[${options[*]}], packages=[${packages[*]}]"

    #如果包是空的直接general处理
    if [ ${#packages[@]} -eq 0 ] ; then
        log "kypackage_general传入参数: ${options[*]}"
        /usr/bin/kypackage_general apt.orig "${operation}" "${options[@]}"
        return 0
    fi
    #is a non-privileged package and cannot be uninstalled
    for package_name in "${packages[@]}"; do
        pkg_env=$(pkg_in_sys $package_name "env")
        pkg_status=$?
        if [ $pkg_status -ne 0 ];then
            printf "软件包 ${package_name} 未安装，所以不会被卸载\n"
        else
            /usr/bin/kypackage_desktop  "--remove" $package_name
            /usr/bin/apt.orig "${operation}" "${options[@]}" "${package_name}"
            local search_result=$(dpkg -l | grep "^ii[[:space:]]\+${package_name}[[:space:]]" 2>/dev/null)
            if [ -z "$search_result" ]; then
                printf "卸载成功，软件包已从核心系统中移除\n"
            fi
        fi
    done
    return 0
}

install_deb()
{
    local absolute_path=$1
    local -n _opts=$2  # 名称引用
    local operation=$3

    if is_package_installed_in_sys "$absolute_path"  && [[ $operation == "install" ]]; then
        pkgname="$(dpkg-deb -f "$absolute_path" Package)"
        pkgversion="$(dpkg-deb -f "$absolute_path" Version)"
        pkg_sys_version=$(pkg_in_sys $pkgname "version")
        dpkg --compare-versions $pkg_sys_version ge $pkgversion
        if [ $? -eq 0 ];then
            printf "软件包已安装在核心系统中\n"
            return 1
        fi
    fi

    if is_package_installed_in_kare "$absolute_path"  && [[ $operation == "install" ]]; then
        pkgname="$(dpkg-deb -f "$absolute_path" Package)"
        pkgversion="$(dpkg-deb -f "$absolute_path" Version)"
        pkg_sys_version=$(pkg_in_sys $pkgname "version")
        dpkg --compare-versions $pkg_sys_version ge $pkgversion
        if [ $? -eq 0 ];then
            printf "软件包已安装在kare容器环境中\n"
            return 1
        fi
    fi

    local result=$(/usr/bin/kypackage_check "$absolute_path" 2> /dev/null)
    if [[ "$result" =~ "将要安装的环境为kare v11" ]]; then
        log "通过kare安装本地软件包: $absolute_path"
        /usr/bin/kypackage_inst "$absolute_path"
    elif [[ "$result" =~ "将要安装的环境为kare v10sp1" ]]; then
        log "通过kare安装本地软件包: $absolute_path"
        /usr/bin/kypackage_inst "$absolute_path"
    else
        package_name="$(dpkg-deb -f "$absolute_path" Package)"
        log "通过kypackage_general安装本地软件包: $absolute_path"

        local check_res
        local check_status
        check_res=$(deb_install_check $package_name $absolute_path)
        check_status=$?
        if [ $check_status -ne 0 ];then
            echo $check_res
            return 1
        fi

        /usr/bin/kypackage_general apt.orig install "${_opts[@]}" "$absolute_path"
        if is_package_installed_in_sys "$absolute_path" ; then
            /usr/bin/kypackage_desktop "--create" "$absolute_path"
            add_to_privilege_list $package_name
            printf "安装成功，安装的环境为核心系统\n"
        fi
    fi
    return 0
}

get_apt_cache_info()
{
    local pkg_name=$1
    local field=$2
    local res
    res=$(apt-cache show ${pkg_name})
    local return_code=$?
    if [ $return_code -ne 0 ];then
        echo $res
    else
        echo $(apt-cache show ${pkg_name} | grep -m 1 ${field} | awk '{print $2}')
    fi
    return $return_code
}

# 专门处理带选项的安装操作
# 注意！先不考虑通配符号支持，是通过apt源码中的CacheSetHelper::PackageFromFnmatch函数实现的，脚本中实现困难
handle_install_with_options() {
    #参数解析
    local operation=$1
    shift
    local options=()
    local packages=()
    
    parse_apt_args packages options "$@"
    options+=("-y")
    log "处理带选项的安装: options=[${options[*]}], packages=[${packages[*]}]"

    #如果包是空的直接general处理
    if [ ${#packages[@]} -eq 0 ] ; then
        log "kypackage_general传入参数: ${options[*]}"
        /usr/bin/kypackage_general apt.orig ${operation} "${options[@]}"
        return 0
    fi

    # 1.区分.deb文件和包名
    local deb_packages=()
    local apt_packages=()
    
    for pkg in "${packages[@]}"; do
        if [[ "$pkg" == *.deb ]]; then
            deb_packages+=("$pkg")
        else
            apt_packages+=("$pkg")
        fi
    done
    
    # 处理.deb文件，使用dpkg安装
    if [ ${#deb_packages[@]} -gt 0 ]; then
        log "处理本地deb包: [${deb_packages[*]}]"
        for deb_file in "${deb_packages[@]}"; do
            absolute_path=$(realpath "$deb_file" 2>/dev/null)
            if [ -f "$absolute_path" ]; then
                log "分析本地软件包: $absolute_path"
                install_deb "$absolute_path" options "$operation"
            else
                log "错误: 文件不存在 $absolute_path"
            fi
        done
    fi
    
    # 处理远程包名，使用apt下载后安装
    if [ ${#apt_packages[@]} -gt 0 ]; then
        if [ -d $apt_cache_dir ]; then
            rm -rf "$apt_cache_dir"
        fi
        mkdir -p $apt_cache_dir
        pushd $apt_cache_dir > /dev/null
        if [ $? -ne 0 ]; then
            log "路径切换失败，退出！"
            return 1
        fi

        if [[ $operation == "reinstall" ]];then
            apt.orig download "${apt_packages[@]}"
        else
            for pkg in "${apt_packages[@]}";do
                local pkg_version
                pkg_version=$(pkg_in_sys $pkg "version")
                pkg_status=$?
                if [ $pkg_status -eq 0 ];then
                    # 系统内有此包，通过apt-cache show获取源内包版本
                    source_pkg_version=$(get_apt_cache_info ${pkg} "Version")
                    source_pkg_status=$?
                    if [ ${source_pkg_status} -ne 0 ];then
                        # 获取源内包信息失败，输出失败信息
                        echo $source_pkg_version
                        continue
                    else
                        dpkg --compare-versions "$pkg_version" ge "$source_pkg_version"
                        if [ $? -eq 0 ];then
                            echo ${pkg}" 已经是最新版 (${pkg_version})"
                            continue
                        fi
                    fi
                fi
                apt.orig download "${pkg}"
            done
        fi
        # 2.逐个包判断安装策略
        for file in *.deb; do
            if [ -f "$file" ]; then
                log "分析软件包: $file"
                deb_name=$(realpath "$file")
                install_deb "$deb_name" options "$operation"
            fi
        done
        popd > /dev/null 2>&1
        rm -rf "$apt_cache_dir"
    fi
    return 0
}

handle_install_in_maintain_mode()
{
    local operation=$1
    shift
    local options=()
    local packages=()
    
    parse_apt_args packages options "$@"
    options+=("-y")
    log "处理带选项的安装: options=[${options[*]}], packages=[${packages[*]}]"

    #如果包是空的直接general处理
    if [ ${#packages[@]} -eq 0 ] ; then
        log "kypackage_general传入参数: ${options[*]}"
        /usr/bin/apt.orig ${operation} "${options[@]}"
        return 0
    fi

    local deb_packages=()
    local apt_packages=()
    
    for pkg in "${packages[@]}"; do
        if [[ "$pkg" == *.deb ]]; then
            deb_packages+=("$pkg")
        else
            apt_packages+=("$pkg")
        fi
    done

    "$ORIGINAL_CMD" "$operation" "$@" 2>&1
    local return_code=$?
    if [ $return_code -eq 0 ]; then
        printf "安装成功，安装的环境为核心系统\n"
        #处理本地包
        if [ ${#deb_packages[@]} -gt 0 ]; then
            log "维护模式下, 处理本地deb包: [${deb_packages[*]}]"
            for deb_file in "${deb_packages[@]}"; do
                absolute_path=$(realpath "$deb_file" 2>/dev/null)
                if [ -f "$absolute_path" ]; then
                    /usr/bin/kypackage_desktop "--create" "$absolute_path"
                    local result=$(/usr/bin/kypackage_check "$absolute_path" 2> /dev/null)
                    if [[ "$result" =~ "将要安装的环境为kare" ]]; then
                        log "维护模式下,非特权包,无需加入特权列表"
                    else
                        package_name="$(dpkg-deb -f "$absolute_path" Package)"
                        add_to_privilege_list $package_name
                        log "维护模式下,特权包加入特权列表"
                    fi
                else
                    log "错误: 文件不存在 $absolute_path"
                fi
            done
        fi
        if [ ${#apt_packages[@]} -gt 0 ]; then
            log "维护模式下, 处理在线deb包: [${apt_packages[*]}]"
            for deb_file in "${apt_packages[@]}"; do
                /usr/bin/kypackage_desktop "--create" "$deb_file"
                add_to_privilege_list $deb_file
                log "维护模式下,在线包加入特权列表"
            done
        fi
    else
        printf "软件包安装失败\n" 2>&1 
        return $return_code
    fi
}


# 只有在非live-build且非chroot且是normal模式时才执行操作拦截
if  should_execute_operation; then
    
    # 需要处理的操作类型
    case "$1" in
        install|reinstall)
            run_by_root
            log "通过wrapper执行操作: $1"
            handle_install_with_options "$@"
            exit $?
            ;;

        remove|purge)
            run_by_root
            log "通过wrapper执行操作: $1"
            handle_remove_with_options "$@"
            exit $?
            ;;

        autoremove|auto-remove|autopurge)
            run_by_root
            log "通过wrapper执行操作: $1"
            /usr/bin/kypackage_general apt.orig "-y" "--allow-downgrades" "$@"
            exit $?
            ;;
            
        upgrade|full-upgrade|dist-upgrade)
            run_by_root
            log "通过wrapper执行操作: $1"
            log "禁止操作: $1"
            printf "当前模式下禁止该操作: $1\n"
            # /usr/bin/kypackage_general "$ORIGINAL_CMD" "$@"
            exit 1
            ;;
        *)
            log "通过原生$ORIGINAL_CMD执行操作: $1"
            exec "$ORIGINAL_CMD" "$@" 2>&1
            ;;
    esac
else
    log "不满足拦截条件，通过原生$ORIGINAL_CMD执行操作: $1"
    case "$1" in
        install|reinstall)
            run_by_root
            handle_install_in_maintain_mode "$@" 2>&1
            exit $?
            ;;
        remove|purge)
            run_by_root
            log "通过wrapper执行操作: $1"
            handle_remove_in_maintain_mode "$@" 2>&1
            exit $?
            ;;
        *)
            exec "$ORIGINAL_CMD" "$@" 2>&1
            ;;
    esac
fi