#!/bin/bash
# set -x 
set -u
source /opt/compatibility_layer/config/build-kare-env.conf

ENVDIRPRE="${KARE_ENV_PATH}/kare-"
ENVDIR="${KARE_ENV_PATH}/kare-u16"
BWRAP_OPTIONS=""
RTE=
CONFIGDIR='/opt/compatibility_layer/config'
EXEDIR='/opt/compatibility_layer/bin'
CONFIGFILE="$CONFIGDIR/configure.ini"
INSTALLLIST="$CONFIGDIR/install.list"
SERVICE_NAME=""
SYSTEM_SERVICE_LIST=()
USER_SERVICE_LIST=()
# 初始化存储子进程 PID 的数组
child_pids=()
TMPFILE=
token=
isCommandLineApplication=false

if [ $(id -u) -eq 0 ]; then
    if [ ! -d $CONFIGDIR ]; then
        mkdir -m 755 -p $CONFIGDIR
        touch $CONFIGFILE $INSTALLLIST
        chmod 664 $CONFIGFILE $INSTALLLIST
    elif [ ! -f $CONFIGFILE ]; then
        touch $CONFIGFILE
        chmod 664 $CONFIGFILE
    elif [ ! -f $INSTALLLIST ]; then
        touch $INSTALLLIST
        chmod 664 $INSTALLLIST
    fi
fi

if [ $(id -u) -eq 0 ]; then
    HOME="/tmp"
fi

logDir=$HOME/.log/compatibility_layer
logFile=$logDir/kare.log
errorLogFile=$logDir/error.log
if [ $(id -u) -eq 0 ]; then
    logDir=/opt/compatibility_layer/logs
    logFile=$logDir/kare.log
    errorLogFile=$logDir/error.log
fi
if [ ! -d $logDir ]; then
    mkdir -p $logDir
    touch $logFile
    touch $errorLogFile
elif [ ! -f $logFile ]; then
    touch $logFile
    touch $errorLogFile
fi

vpWS="/opt/compatibility_layer/vpws"
vpWS_BAK1="/opt/compatibility_layer/vpws1"
vpControlFile="/opt/compatibility_layer/vpws/vp/DEBIAN/control"
vpPostRmFile="/opt/compatibility_layer/vpws/vp/DEBIAN/postrm"

BUSPATH='/opt/compatibility_layer/config/bus'
SESBUSPATH=${BUSPATH}/sessionbus
SYSBUSPATH=${BUSPATH}/systembus
SYSCONFPATH=${SYSBUSPATH}/conf
SYSCONFPATH_=${SYSBUSPATH}/conf_
SESBUSDES=/usr/share/dbus-1/services
SYSBUSDES=/usr/share/dbus-1/system-services
SYSCONFDES=/etc/dbus-1/system.d/
SYSCONFDES_=/usr/share/dbus-1/system.d/
GSETTINGSPATH='/opt/compatibility_layer/config/gsettings'
GSETTINGS=/usr/share/glib-2.0/schemas/

CONFLICTIONPATH=/opt/compatibility_layer/config/bus/confliction
SESCONFLICTIONPATH=${CONFLICTIONPATH}/sesbuslist/
SYSCONFLICTIONPATH=${CONFLICTIONPATH}/sysbuslist/
SYSCONFCONFLICTIONPATH=${CONFLICTIONPATH}/sysconflist/
SYSCONFCONFLICTIONPATH_=${CONFLICTIONPATH}/sysconflist_/
KAREHOST=$(cat /etc/os-release | grep PRETTY_NAME)
driverInstallConfig="/opt/compatibility_layer/config/driver-install.conf"
DriverInstallList="/opt/compatibility_layer/config/driver-install.list"

if [ ! -d ${CONFLICTIONPATH} ]; then
    [ $(id -u) -eq 0 ] && mkdir -p ${CONFLICTIONPATH}
fi

echo -e "\n\n\n" >>$logFile
echo $(date) >>$logFile

trap "echo 'DEBUG - 接收到SIGINT信号' | tee -a $logFile" SIGINT

function printUsage() {
    echo "用法: kare [选项] <命令> [参数]"
    echo "选项说明:"
    echo "  -e                 指定软件包安装环境"
    printf "%-21s%-20s%-20s%-20s%-20s%-20s\n" "" "ubuntu16.04" "ubuntu18.04" "ubuntu20.04" "ubuntu22.04" "ubuntu24.04"
    printf "%-21s%-20s%-20s%-20s\n" "" "v4" "v10" "v10sp1"
    printf "%-21s%-20s%-20s\n" "" "openkylin1.0" "openkylin2.0"
    printf "%-21s%-20s%-20s\n" "" "shadow"
    echo "  -b <参数>          构建兼容运行环境"
    printf "%-21s%-20s%-20s%-20s%-20s%-20s\n" "" "ubuntu16.04" "ubuntu18.04" "ubuntu20.04" "ubuntu22.04" "ubuntu24.04"
    printf "%-21s%-20s%-20s%-20s\n" "" "v4" "v10" "v10sp1"
    printf "%-21s%-20s%-20s\n" "" "openkylin1.0" "openkylin2.0"
    printf "%-21s%-20s%-20s\n" "" "shadow"
    echo "  -E                 列出构建完成的兼容运行环境"
    echo "  -i|install <参数>  安装软件包"
    echo "  -r|remove  <参数>  精确移除软件包(包名 包版本)"
    echo "  -P <参数>          模糊移除软件包(包名)"
    echo "  -l|list            列出已安装的软件包"
    echo "  -L <参数>          列出软件包的已安装文件"
    echo "  -S <参数>          列出文件所在软件包及路径"
    echo "  -f <参数>          修复软件包 补充软件包所需依赖"
    echo "  inspect <参数>     进入软件安装运行环境"
    echo ""
    echo "命令说明:"
    echo "  run <参数>         使用KARE运行软件"
    printf "%-21s%-20s%-20s%-20s%-20s\n" "" "参数说明: <软件包名_软件包版本> <软件执行命令>"
    echo ""
    echo "示例:"
    echo "  kare -e ubuntu16.04 -i softwareName_version_arch.deb"
    echo "  kare -b ubuntu16.04"
    echo "  kare -r softwareName version"
    echo "  kare -P softwareName"
    echo "  kare -l"
    echo "  kare -L softwareName"
    echo "  kare -S filename"
    echo "  kare -f softwareName"
    echo "  kare -E"
    echo "  kare inspect softwareName"
    echo '  kare run softwareName_version exec 或 kare run softwareName exec'
}

containerTypeValue="docker"
# 容器选择器
function containerType() {
    if dpkg -l | grep -qo 'docker\.io\|docker\.ce'; then
        containerTypeValue="docker"
    elif dpkg -l | grep -qo 'bubblewrap'; then
        containerTypeValue="bwrap"
    else
        echo -e "\e[1mkare: \e[31m错误: \e[0m系统不存在支持兼容环境运行的工具"
        exit -1
    fi
    echo "DEBUG - 容器选型结果:${containerTypeValue}" >>$logFile
}

containerNameValue=""
softwareNameValue=""
softwareVersionNum=""
softwareArch=""
softwareTypeValue=""
function splitSoftwareDeb() {
        
        # if dpkg-deb -c $1 | grep -q "/etc/sane.d/" || dpkg-deb -c $1 | grep -q "/usr/share/cups/"; then
        #     softwareTypeValue="v10sp1Driver"
        # fi
        deb_contents=$(dpkg-deb -c "$1" 2>/dev/null)
        if [ $? -ne 0 ]; then
            echo "错误：deb解析失败" >>$logFile
            exit 1
        fi
        saneWhiteList=("drc240_1.00-3_amd64.deb")
        for str in "${saneWhiteList[@]}"; do
            if [ "$str" = "$(basename "$1")" ]; then
                softwareTypeValue="v10sp1Driver"
            fi
        done
        
        if echo "$deb_contents" | grep -q "/etc/sane.d/" || echo "$deb_contents" | grep -q "/usr/share/cups/"; then
            softwareTypeValue="v10sp1Driver"
        fi
        local deb_file=$1
        softwareNameValue=$(dpkg-deb --field $deb_file Package)
        softwareVersionNum=$(dpkg-deb --field $deb_file Version)
        softwareArch=$(dpkg-deb --field $deb_file Architecture)
        softwareNameValue=$(echo $softwareNameValue | sed -r 's/(\+|\/|\\|\~|\%|\:)//g')
        softwareVersionNum=$(echo $softwareVersionNum | sed -r 's/(\+|\/|\\|\~|\%|\:)//g')
        if [ -z "$softwareTypeValue" ]; then
            containerNameValue=${softwareNameValue}_${softwareVersionNum}
        elif [ "$softwareTypeValue" = "v10sp1Driver" ]; then
            containerNameValue="v10sp1Driver"
        fi
}

# 获取 bwrap 绑定命令参数
function getBwrapOption() {
    # source /opt/compatibility_layer/config/build-kare-env.conf
    # if [ "$KARE_ENV_PATH" = "/" ]; then
    #     KARE_PATH="/.$1"
    # else
    #     KARE_PATH="${KARE_ENV_PATH}/.$1"
    # fi
    KARE_PATH="$1"
    # echo $KARE_PATH
    SHAREDDIRS=(
        box
        data
        home
        media
        mnt
        run
        sys
        tmp
	    opt/compatibility_layer/vpws
    )

    KAREDIRS=(
        bin
        etc
        lib
        lib64
        sbin
        usr
        var
    )

    for DIR in "${KAREDIRS[@]}"; do
        if [ -d "$KARE_PATH/$DIR" ]; then
            BWRAP_OPTIONS="$BWRAP_OPTIONS --bind $KARE_PATH/$DIR /$DIR"
        fi
    done

    for DIR in "${SHAREDDIRS[@]}"; do
        if [ -d "/$DIR" ]; then
            BWRAP_OPTIONS="$BWRAP_OPTIONS --bind /$DIR /$DIR"
        fi
    done

    BWRAP_OPTIONS="$BWRAP_OPTIONS --dev-bind /dev /dev --proc /proc"

    BWRAP_OPTIONS="$BWRAP_OPTIONS --setenv DISPLAY :0"
}

function umountOverlay() {
    if [ ! -d "/sysroot" ]; then
        return
    fi
    
    if [ "$containerImage" = "baseimage_ok2" ] || [ "$containerImage" = "baseimage_shadow" ]; then
        umount  /var/kare/$1/merged/*
        rm -rf /var/kare/$1 /home/.kare/$1/overlay  >/dev/null 2>&1
    fi
}

# 容器操作
containerSharedDir=""
SESPORT=28322
SYSPORT=44695
# -e DBUS_SYSTEM_BUS_ADDRESS=tcp:host=localhost,port=${SYSPORT} \
# -e DBUS_SESSION_BUS_ADDRESS=tcp:host=localhost,port=${SESPORT} \
function createContainer() {
    desktop_file_path=
    if [ -d "/sysroot" ]; then
        desktop_file_count=$(dpkg -c "$1" | grep -c "/usr/share/applications/.*\.desktop")
        if [ "$desktop_file_count" -eq 0 ]; then
            [ ! -d "${vpWS_BAK1}" ] && mkdir -p ${vpWS_BAK1}
            : >${vpWS_BAK1}/kare_manager_${containerNameValue}
            while read line; do
                echo $line | sed 's/^\.//; /\/$/d' >> ${vpWS_BAK1}/kare_manager_${containerNameValue}
            done < <(dpkg -c $1 | awk '{print $NF}')
        fi
        if [ "$desktop_file_count" -eq 1 ]; then
            desktop_file_path=/opt/kare$(dpkg -c "$1" | grep -o "/usr/share/applications/.*\.desktop")
        fi
    fi
    virtualHostDir="/hostenv"
    PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
    XDG_CONFIG_DIRS=/etc/xdg/xdg-ukui:/etc/xdg:${virtualHostDir}/etc/xdg/xdg-ukui:${virtualHostDir}/etc/xdg
    XDG_DATA_DIRS="/usr/share/ukui:/usr/local/share/:/usr/share/:\
${virtualHostDir}/usr/share/ukui:${virtualHostDir}/usr/local/share/:${virtualHostDir}/usr/share/"
    USER=$(echo $SUDO_USER)
    # 容器名称
    # 容器环境变量
    if [ "$containerImage" = "baseimage_ok2" ] || [ "$containerImage" = "baseimage_shadow" ]; then
        containerEnv="-e WAYLAND_DISPLAY= \
-e QT_X11_NO_MITSHM=1 \
-e PATH=${PATH} \
-e XDG_RUNTIME_DIR=/run/user/1000 \
-e XDG_DATA_DIRS=${XDG_DATA_DIRS} \
-e XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS} \
-e DISPLAY=:0 \
-e browser_agent_env=true \
-e BROWSER=firefox \
-e USER=${USER} \
-e SYSTEMD_IGNORE_CHROOT=1 \
-e SYSTEMCTL_FORCE_BUS=1 \
-e XDG_SESSION_TYPE=wayland \
-e SHELL=/bin/bash \
-e LOGNAME=${USER} \
-e PANSHI_APP_DESKTOP=${desktop_file_path}" 
    else
        containerEnv="-e DBUS_SYSTEM_BUS_ADDRESS=tcp:host=localhost,port=${SYSPORT} -e WAYLAND_DISPLAY= \
-e DBUS_SESSION_BUS_ADDRESS=tcp:host=localhost,port=${SESPORT} \
-e QT_X11_NO_MITSHM=1 \
-e PATH=${PATH} \
-e XDG_RUNTIME_DIR=/run/user/1000 \
-e XDG_DATA_DIRS=${XDG_DATA_DIRS} \
-e XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS} \
-e DISPLAY=:0 \
-e browser_agent_env=true \
-e BROWSER=firefox \
-e USER=${USER} \
-e XDG_SESSION_TYPE=x11 \
-e SHELL=/bin/bash \
-e LOGNAME=${USER} \
-e PANSHI_APP_DESKTOP=${desktop_file_path}" 
    fi
    [ -d "/sysroot" ] && containerEnv="${containerEnv} -e IMMU=true"

    # 容器特殊参数
    containerSpecialParam=""
    case "${containerNameValue}" in
    todesk*)
        containerSpecialParam="--network=host"
        ;;
    *)
        ;;
    esac

    # 容器登录用户
    containerUser=$(id -u)
    # 容器共享目录
    excludeDirList=(/backup
        /cdrom
        /lost+found
        /fs.old
        /usr
        /opt
        /boot
        /etc
        /root
        /srv
        /var
        /bin
        /lib
        /lib64
        /lib32
        /libx32
        /sbin
        /proc
        /kare-)
    containerSharedDir=$containerSharedDir" -v /etc:${virtualHostDir}/etc:ro -v /usr:${virtualHostDir}/usr:ro"
    containerSharedDir=$containerSharedDir" -v /etc/localtime:/etc/localtime -v /etc/timezone:/etc/timezone"

    for each in /*; do
        # 过滤非目录和链接目录
        if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
        fi
        if [ $each == "/dev" ]; then
            containerSharedDir=$containerSharedDir" -v $each:$each"
        elif [ $each == "/home" ]; then
            containerSharedDir=$containerSharedDir" -v $each:$each"
        elif [ $each == "/media" ]; then
            containerSharedDir=$containerSharedDir" -v $each:$each"
        elif [ $each == "/mnt" ]; then
            containerSharedDir=$containerSharedDir" -v $each:$each"
        elif [ $each == "/tmp" ]; then
            containerSharedDir=$containerSharedDir" -v $each:$each"
        elif [ $each == "/data" ]; then
            containerSharedDir=$containerSharedDir" -v $each:$each"
        # /proc 进程信息需要
        elif [ $each == "/proc" ] && [ "${ENVDIR}" == "${ENVDIRPRE}v10sp1" ]; then
            containerSharedDir=$containerSharedDir" -v $each:$each"
        # /sys 外设相关
        elif [ $each == "/sys" ]; then
            if [[ "${KAREHOST}" =~ "openKylin 2.0" ]] && [ -d "/sys/fs/selinux" ]; then
                for eachd in ${each}/*; do
                    if [ "${eachd}" = "${each}/fs" ]; then
                        for eachdd in ${eachd}/*; do
                            [ "${eachdd}" != "${eachd}/selinux" ] && containerSharedDir=$containerSharedDir" -v $eachdd:$eachdd"
                        done
                    else
                        containerSharedDir=$containerSharedDir" -v $eachd:$eachd"
                    fi
                done
            else
                containerSharedDir=$containerSharedDir" -v $each:$each"
            fi
        # 输入法需要
        elif [ $each == "/run" ]; then
            for item in "$each"/*; do
            # 检查是否是目录
            if [ -d "$item" ]; then
                # 获取目录名（不包括路径）
                dirname=$(basename "$item")
                # 检查目录名是否不等于 "cups"
                if [ "$dirname" != "cups" ]; then
                    containerSharedDir=$containerSharedDir" -v $each/$dirname:$each/$dirname"
                fi
            fi
            done
        elif [ $each == "/opt" ]; then
            containerSharedDir=$containerSharedDir" -v $each/compatibility_layer/config/bus/:$each/compatibility_layer/config/bus/"
            containerSharedDir=$containerSharedDir" -v $each/compatibility_layer/bin/:$each/compatibility_layer/bin/"
            containerSharedDir=$containerSharedDir" -v $each/compatibility_layer/logs/:$each/compatibility_layer/logs/"
            # 必要目录挂载完毕，寻找是否有自建目录
        else
            flag=0
            for tmpItem in ${excludeDirList[@]}; do
                if [[ $each == $tmpItem* ]]; then
                    flag=1
                    break
                else
                    flag=0
                    continue
                fi
            done
            if [ $flag -eq 0 ]; then
                echo "找到用户自建目录: $each" >>$logFile
                containerSharedDir=$containerSharedDir" -v $each:$each"
            fi
        fi
    done

    if [ "$containerImage" = "baseimage_ok2" ] || [ "$containerImage" = "baseimage_shadow" ]; then
        OK2KAREDIRS=(
            bin
            lib
            lib64
            sbin
            var
            usr
        )
        # 构建overlay
        for DIR in "${OK2KAREDIRS[@]}"; do
            [ ! -d "/home/.kare/$containerNameValue/overlay/upper/$DIR" ] && mkdir -p "/home/.kare/$containerNameValue/overlay/upper/$DIR"
            [ ! -d "/home/.kare/$containerNameValue/overlay/work/$DIR" ] && mkdir -p "/home/.kare/$containerNameValue/overlay/work/$DIR"
            [ ! -d "/var/kare/$containerNameValue/merged/$DIR" ] && mkdir -p "/var/kare/$containerNameValue/merged/$DIR"
            mount -t overlay  overlay -o lowerdir=/$DIR,upperdir=/home/.kare/$containerNameValue/overlay/upper/$DIR,workdir=/home/.kare/$containerNameValue/overlay/work/$DIR /var/kare/$containerNameValue/merged/$DIR
            containerSharedDir=$containerSharedDir" -v /var/kare/$containerNameValue/merged/$DIR:/$DIR"
        done
        # 删除status文件
        mv /var/kare/$containerNameValue/merged/var/lib/dpkg /var/kare/$containerNameValue/merged/var/lib/dpkg.bak
        cp -r /var/lib/dpkg /var/kare/$containerNameValue/merged/var/lib/
        containerSharedDir=$containerSharedDir" -v /etc/dpkg/plugins:/etc/dpkg/plugins -v /opt/certaide.kylin:/opt/certaide.kylin -v /etc/apt/sources.list:/etc/apt/sources.list "
        containerCreateCmd="$containerTypeValue create --privileged --ipc host $containerSpecialParam -u 1000 -it --name $containerNameValue $containerEnv $containerSharedDir $containerImage"
    else 
        containerCreateCmd="$containerTypeValue create --privileged --ipc host --pid host $containerSpecialParam -u 1000 -it --name $containerNameValue $containerEnv $containerSharedDir $containerImage"
    fi
    # 创建容器
    # containerCreateCmd="$containerTypeValue create --privileged -u 1000 -it --name $containerNameValue $containerEnv $containerSharedDir $containerImage"
    # echo "DEBUG - 容器创建命令: $containerCreateCmd"
    if [ "$containerNameValue" = "v10sp1Driver" ];then
        containerCreateCmd="${containerCreateCmd// -e DBUS_SESSION_BUS_ADDRESS=tcp:host=localhost,port=28322/}"
        containerCreateCmd="${containerCreateCmd// -e DBUS_SYSTEM_BUS_ADDRESS=tcp:host=localhost,port=44695/}"
    fi
    $containerCreateCmd >>$logFile 2>&1
    if [ $? -eq 0 ]; then
        echo "DEBUG - 容器${containerNameValue}创建成功" >>$logFile
    else
        echo "ERROR - 容器${containerNameValue}创建失败" >>$logFile
        [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
        return -1
    fi
}

containerImagePre="baseimage_"
containerImage="baseimage_v10"
iconFileList=
iconFileListLn=
RichLF=0
function Abandon() {
    # dpkg 查询存在的软件包，包括使用 dpkg 安装的和kare安装的虚包
    if dpkg -l | awk '$0 ~ /^ii/{print $2}' | grep -xq ${softwareNameValue}; then
        if ! grep $softwareNameValue $INSTALLLIST &>/dev/null; then
            # dpkg 安装的软件包
            echo -1
            return
        fi
        if [ $(grep $softwareNameValue $INSTALLLIST | awk -F= '{print $3}') != "$RTE" ]; then
            # kare 安装的软件包 但是运行环境不匹配
            echo -2
            return
        fi
        # kare 安装的软件包 且运行环境匹配
        RichLF=1
        echo 1
        return
    fi
    # dpkg 查询不存在的软件包，包括未安装和kare不安装虚包的情况
    if ! grep $softwareNameValue $INSTALLLIST &>/dev/null; then
        # 未安装的软件包
        echo 0
        return
    fi
    if [ $(grep $softwareNameValue $INSTALLLIST | awk -F= '{print $3}') != "$RTE" ]; then
        # kare 安装的软件包 但是运行环境不匹配
        echo -2
        return
    fi
    # kare 安装的软件包 且运行环境匹配
    RichLF=1
    echo 1
    return
}

function RichL() {
    echo -e "\e[1mkare: \e[33m警告: \e[0m$softwareNameValue reinstall ..." | tee -a $logFile
    removeFunP $softwareNameValue &>/dev/null
    installFun $1
}

function installFun() {
    SRV_LAUNCH_SCRIPT="/usr/bin/kare run"
    SRVCMD=
    for x in $vpWS/vp/*; do
        if [ $x != "$vpWS/vp/DEBIAN" ]; then
            rm -rf $x
        fi
    done
    python3 "$EXEDIR/srvclient.py" "docker" "$containerNameValue" "$1"
    # cpServiceFile $1
    if [ ${containerTypeValue} == "docker" ]; then
        echo "DEBUG - 软件包-$1 对应的容器名称为-$containerNameValue 软件包名称为-$softwareNameValue 版本号为-$softwareVersionNum" >>$logFile
        if [ -z "$softwareTypeValue" ]; then
            createContainer "$1"
        else
            if docker ps -a | grep -q "$containerNameValue"; then
                echo "DEBUG -  软件包-$1 对应的容器名称为-$containerNameValue 已经存在无需创建新容器" >>$logFile
                $containerTypeValue start "$containerNameValue"
            else
                createContainer "$1"
            fi
        fi
        
            if [ $? -eq 0 ]; then
                echo "DEBUG - 容器创建成功" >>$logFile
            else
                echo "ERROR - 容器创建失败" >>$logFile
                if ! docker images | grep -q "baseimage_"; then
                    echo "ERROR - 无基础环境, 请使用kare -b 构建基础环境" | tee -a $logFile
                    $containerTypeValue rm -f $containerNameValue &>/dev/null
                    umountOverlay $containerNameValue
                    [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
                    exit -1
                fi
                echo "ERROR - 容器创建失败导致软件包安装失败,请检查软件包名是否符合规范后重新安装" | tee -a $logFile
                $containerTypeValue rm -f $containerNameValue &>/dev/null
                umountOverlay $containerNameValue
                [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
                exit -1
            fi
			if [ "$containerImage" != "baseimage_ok2" ] && [ "$containerImage" != "baseimage_shadow" ];then
                containerCpDebCmd="$containerTypeValue cp "$1" $containerNameValue:/"
                echo "DEBUG - 复制安装包至容器命令: $containerCpDebCmd" >>$logFile
                $containerCpDebCmd >>$logFile 2>&1
                if [ $? -eq 0 ]; then
                    echo "DEBUG - 安装包 $1 复制成功" >>$logFile
                else
                    echo "ERROR - 安装包 $1 复制失败" >>$logFile
                    echo "ERROR - 软件包复制失败导致软件包安装失败,请尝试使用软件包绝对路径重新安装" | tee -a $logFile
                    $containerTypeValue rm -f $containerNameValue >/dev/null
                    umountOverlay $containerNameValue
                    [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
                    exit -1
                fi
                if [ -f "${ENVDIR}/usr/bin/sudo" ]; then
                    containerCpSudoCmd="$containerTypeValue cp "$ENVDIR/usr/bin/sudo" $containerNameValue:/usr/bin/"
                else
                    echo "ERROR - ${ENVDIR}/usr/bin/sudo 不存在" | tee -a $logFile
                    $containerTypeValue rm -f $containerNameValue >/dev/null
                    umountOverlay $containerNameValue
                    [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
                    exit -1
                fi
                echo "DEBUG - 复制sudo至容器命令: $containerCpSudoCmd" >>$logFile
                $containerCpSudoCmd >>$logFile 2>&1
                if [ $? -eq 0 ]; then
                    echo "DEBUG - 4755权限的sudo复制成功" >>$logFile
                else
                    echo "ERROR - 4755权限的sudo复制失败" >>$logFile
                    echo "ERROR - sudo复制失败,请确认${ENVDIR}/usr/bin/sudo存在并重新安装" | tee -a $logFile
                    $containerTypeValue rm -f $containerNameValue >/dev/null
                    umountOverlay $containerNameValue
                    [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
                    exit -1
                fi
			fi
            $containerTypeValue start $containerNameValue >>$logFile 2>&1            
			if [ "$containerImage" = "baseimage_ok2" ] || [ "$containerImage" = "baseimage_shadow" ]; then
                docker cp /opt/compatibility_layer/config/container-init $containerNameValue:/usr/bin/
                docker cp /opt/compatibility_layer/config/hostAgent $containerNameValue:/usr/bin/
                docker cp /opt/compatibility_layer/config/host-spawn $containerNameValue:/usr/bin/
                docker cp /opt/compatibility_layer/config/dbus-daemon-proxy $containerNameValue:/usr/bin/
                docker cp /opt/compatibility_layer/config/add_namespace_to_conflicted_dbus.sh $containerNameValue:/usr/bin/
                docker cp /opt/compatibility_layer/config/env/check_depends.py $containerNameValue:/usr/bin/
                docker cp /opt/compatibility_layer/config/kare-apt.py $containerNameValue:/usr/bin/
            fi
            if [ $? -ne 0 ]; then
                echo "ERROR - 容器$containerNameValue启动失败" >>$logFile
                echo "ERROR - 容器启动失败,详细原因请查看${logFile},解决问题后请重新安装" | tee -a $logFile
                $containerTypeValue rm -f $containerNameValue >/dev/null
                umountOverlay $containerNameValue
                [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
                exit -1
            else
                echo "DEBUG - 容器$containerNameValue启动成功" >>$logFile
                if [ "$softwareNameValue" = "redisplus" ]; then 
                    $containerTypeValue exec -d $containerNameValue /bin/bash -c "echo qwer1234 | sudo -S mkdir -p /usr/share/desktop-directories/"
                fi
            fi
            if [ "$containerImage" = "baseimage_v10sp1" ];then
                $containerTypeValue exec --user root $containerNameValue /bin/bash /usr/bin/sym-link
            fi
            if [ "$containerImage" = "baseimage_u24" ];then
                $containerTypeValue exec --user root $containerNameValue /bin/bash /usr/bin/sym-link
            fi
            if [ "$containerImage" = "baseimage_ok2" ] || [ "$containerImage" = "baseimage_shadow" ]; then
                $containerTypeValue exec --user root $containerNameValue /bin/bash /usr/bin/container-init $1 | tee -a $logFile
            else
                $containerTypeValue exec $containerNameValue /bin/bash /usr/bin/container-init $1 | tee -a $logFile
			    # $containerTypeValue exec --user root $containerNameValue python3 "$EXEDIR/aptclient.py" $1 | tee -a $logFile
            fi

            pipestatus=("${PIPESTATUS[@]}")
            if [ "${pipestatus[0]}" -eq 0 ]; then
                echo "DEBUG - 软件包$1安装成功" >>$logFile
                if [ "$softwareNameValue" = "cn.com.dzh" ] && [ "$softwareArch" = "amd64" ]; then 
                    $containerTypeValue exec --user root $containerNameValue /bin/bash -c "/usr/bin/ln -s /usr/lib/x86_64-linux-gnu/libdl-2.31.so /opt/apps/cn.com.dzh/files/bin/libdl.so"
                fi
                if [ "$containerNameValue" = "v10sp1Driver" ];then
                    if ps -ef | grep -v grep | grep -q "/usr/sbin/cupsd -f";then
                         echo "DEBUG - cupsd服务已经存在，无需启动" | tee -a $logFile
                    else
                        $containerTypeValue exec -d --user root $containerNameValue /bin/bash -c "/usr/sbin/cupsd -f "
                    fi
                    $containerTypeValue exec -d $containerNameValue /bin/bash -c "cupsctl --share-printers"
                    $containerTypeValue exec -d $containerNameValue /bin/bash -c "cupsctl --remote-any"

                    if ps -ef | grep -v grep | grep -q "/usr/sbin/saned -a";then
                         echo "DEBUG - saned服务已经存在，无需启动" | tee -a $logFile
                    else
                        $containerTypeValue exec -d --user root $containerNameValue /bin/bash -c "/usr/sbin/saned -a"
                    fi
                    #TODO 将容器内ip同步至宿主机net.conf ，校准saned.conf是否存在128.128.0.1
                    # 宿主机文件修改
                    saneip=`docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' v10sp1Driver`
                    if ! grep -q $saneip /etc/sane.d/net.conf; then
                        echo $saneip >> /etc/sane.d/net.conf
                    fi
                    if ! grep -q '128.128.0.1' /etc/sane.d/saned.conf; then
                        echo '128.128.0.1' >> /etc/sane.d/saned.conf
                    fi
                    $containerTypeValue exec -d --user root $containerNameValue /bin/bash -c "bash /usr/bin/share-sane.sh"
                    # 容器内文件修改
                    /usr/bin/kare_setup_printer.sh
                    if ps -ef | grep -v grep | grep -q "/usr/bin/kare-ippfind.py"; then
                        echo "DEBUG - ippfind服务已经存在，无需启动" | tee -a $logFile
                    else
                        nohup python3 /usr/bin/kare-ippfind.py >/dev/null 2>&1 &
                    fi
                fi
                pids=$(pgrep -f $(basename "$1")"_log")  
                for pid in $pids; do  
                    # ppid=$(ps -o ppid= -p $pid)  
                    kill -9 $pid > /dev/null 2>&1
                done  
            else
                echo "ERROR - 软件包$1安装失败" | tee -a $logFile
                $containerTypeValue rm -f $containerNameValue >/dev/null
                umountOverlay $containerNameValue
                [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
                exit -1
            fi
            sleep 1
            $containerTypeValue start $containerNameValue >>$logFile 2>&1
            $containerTypeValue exec $containerNameValue ls /usr/share/dbus-1/services >${SESBUSPATH}/sesbus2.list
            $containerTypeValue exec $containerNameValue ls /usr/share/dbus-1/system-services >${SYSBUSPATH}/sysbus2.list
            $containerTypeValue exec $containerNameValue ls /etc/dbus-1/system.d >${SYSCONFPATH}/sysconf2.list
            $containerTypeValue exec $containerNameValue ls /usr/share/dbus-1/system.d/ >${SYSCONFPATH_}/sysconf2_.list
            $containerTypeValue exec $containerNameValue ls /usr/share/glib-2.0/schemas/ >${GSETTINGSPATH}/gsettings2.list
            $containerTypeValue exec -u root $containerNameValue /bin/bash -c "/usr/bin/python3 /usr/bin/check_depends.py ${softwareNameValue}"
            diff ${GSETTINGSPATH}/gsettings2.list ${GSETTINGSPATH}/gsettings.list | awk -F "< " '/^< /{print $2}' | while read EACHSETTINGS; do
                if ls /usr/share/glib-2.0/schemas/ | grep -q ${EACHSETTINGS}; then continue; fi
                ! grep -q "${EACHSETTINGS}" ${GSETTINGSPATH}/gsettings.diff && echo "${EACHSETTINGS}" >>${GSETTINGSPATH}/gsettings.diff
                [ ! -d "${vpWS}/vp/${GSETTINGS}" ] && mkdir -p ${vpWS}/vp/${GSETTINGS}
                if [ -d "/sysroot" ]; then
                    $containerTypeValue cp $containerNameValue:/usr/share/glib-2.0/schemas/${EACHSETTINGS} ${vpWS}/vp/usr/share/schemas/
                else
                    $containerTypeValue cp $containerNameValue:/usr/share/glib-2.0/schemas/${EACHSETTINGS} ${vpWS}/vp/${GSETTINGS}
                fi
            done
            if [ -d "/sysroot" ]; then
                if [ -d "/opt/kare/usr/share/glib-2.0/schemas/" ]; then
                    glib-compile-schemas /opt/kare/usr/share/glib-2.0/schemas/
                fi
            else
                if [ -d "/usr/share/glib-2.0/schemas/" ]; then
                    glib-compile-schemas /usr/share/glib-2.0/schemas/
                fi
            fi
            diff ${SESBUSPATH}/sesbus2.list ${SESBUSPATH}/sesbus.list | awk -F "< " '/^< /{print $2}' | while read EACHSES; do
                # grep -q "${EACHSES}" ${SESBUSPATH}/sesbus.diff && continue
                if ls /usr/share/dbus-1/services/ | grep -q ${EACHSES}; then
                    echo "${EACHSES}" >>${SESBUSPATH}/sesbus.same
                    echo "\e[1mkare: \e[31mDEBUG: \e[0m session bus conflict file: $EACHSES" >> $logFile
                else
                ! grep -q "${EACHSES}" ${SESBUSPATH}/sesbus.diff && echo "${EACHSES}" >>${SESBUSPATH}/sesbus.diff
                [ ! -d "${vpWS}/vp/${SESBUSDES}" ] && mkdir -p ${vpWS}/vp/${SESBUSDES}
                $containerTypeValue cp $containerNameValue:/usr/share/dbus-1/services/${EACHSES} ${vpWS}/vp/${SESBUSDES}
                sed -i "s|^Exec=|Exec=${SRV_LAUNCH_SCRIPT} ${containerNameValue} |" ${vpWS}/vp/${SESBUSDES}/${EACHSES}
                fi
            done
            diff ${SYSBUSPATH}/sysbus2.list ${SYSBUSPATH}/sysbus.list | awk -F "< " '/^< /{print $2}' | while read EACHSYS; do
                # grep -q "${EACHSYS}" ${SYSBUSPATH}/sysbus.diff && continue
                if ls /usr/share/dbus-1/system-services/ | grep -q ${EACHSYS}; then
                    echo "${EACHSYS}" >>${SYSBUSPATH}/sysbus.same
                    echo "\e[1mkare: \e[31mDEBUG: \e[0m system bus conflict file: $EACHSYS"  >> $logFile
                else
                ! grep -q "${EACHSYS}" ${SYSBUSPATH}/sysbus.diff && echo "${EACHSYS}" >>${SYSBUSPATH}/sysbus.diff
                [ ! -d "${vpWS}/vp/${SYSBUSDES}" ] && mkdir -p ${vpWS}/vp/${SYSBUSDES}
                $containerTypeValue cp $containerNameValue:/usr/share/dbus-1/system-services/${EACHSYS} ${vpWS}/vp/${SYSBUSDES}
                sed -i "s|^Exec=|Exec=${SRV_LAUNCH_SCRIPT} ${containerNameValue} |" ${vpWS}/vp/${SYSBUSDES}/${EACHSYS}
                fi
            done
            diff ${SYSCONFPATH}/sysconf2.list ${SYSCONFPATH}/sysconf.list | awk -F "< " '/^< /{print $2}' | while read EACHCONF; do
                # grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && continue
                if ls /etc/dbus-1/system.d/ | grep -q ${EACHCONF}; then
                    echo "${EACHCONF}" >>${SYSCONFPATH}/sysconf.same
                else
                ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && echo "${EACHCONF}" >>${SYSCONFPATH}/sysconf.diff
                [ ! -d "${vpWS}/vp/${SYSCONFDES}" ] && mkdir -p ${vpWS}/vp/${SYSCONFDES}
                $containerTypeValue cp $containerNameValue:/etc/dbus-1/system.d/${EACHCONF} ${vpWS}/vp/${SYSCONFDES}
                fi
            done
            diff ${SYSCONFPATH_}/sysconf2_.list ${SYSCONFPATH_}/sysconf_.list | awk -F "< " '/^< /{print $2}' | while read EACHCONF; do
                if ls ${SYSCONFDES_} | grep -q ${EACHCONF}; then
                    echo "${EACHCONF}" >>${SYSCONFPATH_}/sysconf_.same
                else
                ! grep -q "${EACHCONF}" ${SYSCONFPATH_}/sysconf_.diff && echo "${EACHCONF}" >>${SYSCONFPATH_}/sysconf_.diff
                [ ! -d "${vpWS}/vp/${SYSCONFDES_}" ] && mkdir -p ${vpWS}/vp/${SYSCONFDES_}
                $containerTypeValue cp $containerNameValue:/usr/share/dbus-1/system.d/${EACHCONF} ${vpWS}/vp/${SYSCONFDES_}
                fi
            done
            echo "正在设置 KARE 服务代理 ..."
            $containerTypeValue exec -d $containerNameValue /bin/bash -c "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus /usr/bin/dbus-daemon-proxy --verbose --session --port ${SESPORT} --namespace $softwareNameValue"
            if [ "$containerImage" != "baseimage_ok2" ] && [ "$containerImage" != "baseimage_shadow" ];then
                $containerTypeValue exec -d $containerNameValue /bin/bash -c "echo qwer1234 | sudo -S /usr/bin/dbus-daemon-proxy --verbose --system --port ${SYSPORT} --namespace $softwareNameValue"
            fi
            if cat ${SESBUSPATH}/sesbus.same >/dev/null || cat ${SYSBUSPATH}/sysbus.same >/dev/null; then
                if [ "$containerImage" != "baseimage_ok2" ] && [ "$containerImage" != "baseimage_shadow" ];then
                    $containerTypeValue exec $containerNameValue /bin/bash -c "echo qwer1234 | sudo -S /bin/bash /usr/bin/add_namespace_to_conflicted_dbus.sh ${SYSBUSPATH}/sysbus.same ${SESBUSPATH}/sesbus.same ${SYSCONFPATH}/sysconf.same .$softwareNameValue $containerNameValue"
                    pipestatus=("${PIPESTATUS[@]}")
                    if [ "${pipestatus[0]}" -ne 0 ]; then
                        echo "\e[1mkare: \e[31m错误: \e[0m执行dbus-proxy冲突脚本失败" >> $logFile
                    else
                        ls ${SESCONFLICTIONPATH} | while read EACHSESFILE; do
                            echo "\e[1mkare: \e[31m测试9: \e[0m $EACHSESFILE" >> $logFile
                            mv ${SESCONFLICTIONPATH}${EACHSESFILE} $SESBUSDES
                        done
                        ls ${SYSCONFLICTIONPATH} | while read EACHSYSFILE; do
                            echo "\e[1mkare: \e[31m测试10: \e[0m $EACHSYSFILE" >> $logFile
                            mv ${SYSCONFLICTIONPATH}${EACHSYSFILE} $SYSBUSDES
                        done
                        ls ${SYSCONFCONFLICTIONPATH} | while read EACHSYSCONFFILE; do
                            echo "\e[1mkare: \e[31m测试11: \e[0m $EACHSYSCONFFILE" >> $logFile
                            mv ${SYSCONFCONFLICTIONPATH}${EACHSYSCONFFILE} $SYSCONFDES
                        done
                        ls ${SYSCONFCONFLICTIONPATH_} | while read EACHSYSCONFFILE_; do
                            echo "\e[1mkare: \e[31m测试12: \e[0m ${EACHSYSCONFFILE_}" >> $logFile
                            mv ${SYSCONFCONFLICTIONPATH_}${EACHSYSCONFFILE_} ${SYSCONFDES_}
                        done
                    fi
                fi
            fi
    elif [ ${containerTypeValue} == "bwrap" ]; then
        # bwrap安装逻辑
        echo "DEBUG - 软件包-$1 对应的容器名称为-$containerNameValue 软件包名称为-$softwareNameValue 版本号为-$softwareVersionNum" >>$logFile

        if [ -d $KARE_PATH ]; then
            sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS apt install -y $1
            pipestatus=("${PIPESTATUS[@]}")
            if [ "${pipestatus[0]}" -eq 0 ]; then
                echo "DEBUG - 软件包$1安装成功" >>$logFile
            else
                echo "ERROR - 软件包$1安装失败" | tee -a $logFile
                exit -1
            fi
        else
            echo "当前指定基础环境不存在，请使用' sudo kare -b '构建后重试。" | tee -a $logFile
            exit -1
        fi

        sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS ls /usr/share/dbus-1/services >${SESBUSPATH}/sesbus2.list
        sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS ls /usr/share/dbus-1/system-services >${SYSBUSPATH}/sysbus2.list
        sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS ls /etc/dbus-1/system.d >${SYSCONFPATH}/sysconf2.list
        sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS ls /usr/share/glib-2.0/schemas/ >${GSETTINGSPATH}/gsettings2.list

        diff ${GSETTINGSPATH}/gsettings2.list ${GSETTINGSPATH}/gsettings.list | awk -F "< " '/^< /{print $2}' | while read EACHSETTINGS; do
            if ls /usr/share/glib-2.0/schemas/ | grep -q ${EACHSETTINGS}; then continue; fi
            ! grep -q "${EACHSETTINGS}" ${GSETTINGSPATH}/gsettings.diff && echo "${EACHSETTINGS}" >>${GSETTINGSPATH}/gsettings.diff
            [ ! -d "${vpWS}/vp/${GSETTINGS}" ] && mkdir -p ${vpWS}/vp/${GSETTINGS}
            sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS cp /usr/share/glib-2.0/schemas/${EACHSETTINGS} ${vpWS}/vp/${GSETTINGS}
        done
        if [ -d "/usr/share/glib-2.0/schemas/" ]; then
            glib-compile-schemas /usr/share/glib-2.0/schemas/
        fi

        diff ${SESBUSPATH}/sesbus2.list ${SESBUSPATH}/sesbus.list | awk -F "< " '/^< /{print $2}' | while read EACHSES; do
            # grep -q "${EACHSES}" ${SESBUSPATH}/sesbus.diff && continue
            if ls /usr/share/dbus-1/services/ | grep -q ${EACHSES}; then
                echo "${EACHSES}" >>${SESBUSPATH}/sesbus.same
                echo -e "\e[1mkare: \e[31mDEBUG: \e[0m session bus conflict file: $EACHSES"  | tee -a $logFile
            else
            ! grep -q "${EACHSES}" ${SESBUSPATH}/sesbus.diff && echo "${EACHSES}" >>${SESBUSPATH}/sesbus.diff
            [ ! -d "${vpWS}/vp/${SESBUSDES}" ] && mkdir -p ${vpWS}/vp/${SESBUSDES}
            sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS cp /usr/share/dbus-1/services/${EACHSES} ${vpWS}/vp/${SESBUSDES}
            sed -i "s|^Exec=|Exec=${SRV_LAUNCH_SCRIPT} ${containerNameValue} |" ${vpWS}/vp/${SESBUSDES}/${EACHSES}
            fi
        done

        diff ${SYSBUSPATH}/sysbus2.list ${SYSBUSPATH}/sysbus.list | awk -F "< " '/^< /{print $2}' | while read EACHSYS; do
            # grep -q "${EACHSYS}" ${SYSBUSPATH}/sysbus.diff && continue
            if ls /usr/share/dbus-1/system-services/ | grep -q ${EACHSYS}; then
                echo "${EACHSYS}" >>${SYSBUSPATH}/sysbus.same
                echo -e "\e[1mkare: \e[31mDEBUG: \e[0m system bus conflict file: $EACHSYS"  | tee -a $logFile
            else
            ! grep -q "${EACHSYS}" ${SYSBUSPATH}/sysbus.diff && echo "${EACHSYS}" >>${SYSBUSPATH}/sysbus.diff
            [ ! -d "${vpWS}/vp/${SYSBUSDES}" ] && mkdir -p ${vpWS}/vp/${SYSBUSDES}
            sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS cp /usr/share/dbus-1/system-services/${EACHSYS} ${vpWS}/vp/${SYSBUSDES}
            sed -i "s|^Exec=|Exec=${SRV_LAUNCH_SCRIPT} ${containerNameValue} |" ${vpWS}/vp/${SYSBUSDES}/${EACHSYS}
            fi
        done

        diff ${SYSCONFPATH}/sysconf2.list ${SYSCONFPATH}/sysconf.list | awk -F "< " '/^< /{print $2}' | while read EACHCONF; do
            # grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && continue
            if ls /etc/dbus-1/system.d/ | grep -q ${EACHCONF}; then
                echo "${EACHCONF}" >>${SYSCONFPATH}/sysconf.same
            else
            ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && echo "${EACHCONF}" >>${SYSCONFPATH}/sysconf.diff
            [ ! -d "${vpWS}/vp/${SYSCONFDES}" ] && mkdir -p ${vpWS}/vp/${SYSCONFDES}
            sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS cp /etc/dbus-1/system.d/${EACHCONF} ${vpWS}/vp/${SYSCONFDES}
            fi
        done
        diff ${SYSCONFPATH_}/sysconf2_.list ${SYSCONFPATH_}/sysconf_.list | awk -F "< " '/^< /{print $2}' | while read EACHCONF; do
            if ls ${SYSCONFDES_} | grep -q ${EACHCONF}; then
                echo "${EACHCONF}" >>${SYSCONFPATH_}/sysconf_.same
            else
            ! grep -q "${EACHCONF}" ${SYSCONFPATH_}/sysconf_.diff && echo "${EACHCONF}" >>${SYSCONFPATH_}/sysconf_.diff
            [ ! -d "${vpWS}/vp/${SYSCONFDES_}" ] && mkdir -p ${vpWS}/vp/${SYSCONFDES_}
            sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS cp /usr/share/dbus-1/system.d/${EACHCONF} ${vpWS}/vp/${SYSCONFDES_}
            fi
        done
        echo "正在设置 KARE 服务代理 ..."
        sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS /bin/bash -c "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus /usr/bin/dbus-daemon-proxy --verbose --session --port ${SESPORT} --namespace $softwareNameValue"
        if [ "$containerImage" != "baseimage_ok2" ] && [ "$containerImage" != "baseimage_shadow" ];then
            sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS /bin/bash -c "echo qwer1234 | sudo -S /usr/bin/dbus-daemon-proxy --verbose --system --port ${SYSPORT} --namespace $softwareNameValue"
        fi
        if cat ${SESBUSPATH}/sesbus.same >/dev/null || cat ${SYSBUSPATH}/sysbus.same >/dev/null; then
            if [ "$containerImage" != "baseimage_ok2" ] && [ "$containerImage" != "baseimage_shadow" ];then
                sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS /bin/bash -c "echo qwer1234 | sudo -S /bin/bash /usr/bin/add_namespace_to_conflicted_dbus.sh ${SYSBUSPATH}/sysbus.same ${SESBUSPATH}/sesbus.same ${SYSCONFPATH}/sysconf.same .$softwareNameValue $containerNameValue"
                pipestatus=("${PIPESTATUS[@]}")
                if [ "${pipestatus[0]}" -ne 0 ]; then
                    echo -e "\e[1mkare: \e[31m错误: \e[0m执行dbus-proxy冲突脚本失败" | tee -a $logFile
                else
                    ls ${SESCONFLICTIONPATH} | while read EACHSESFILE; do
                        echo -e "\e[1mkare: \e[31m测试9: \e[0m $EACHSESFILE"
                        mv ${SESCONFLICTIONPATH}${EACHSESFILE} $SESBUSDES
                    done
                    ls ${SYSCONFLICTIONPATH} | while read EACHSYSFILE; do
                        echo -e "\e[1mkare: \e[31m测试10: \e[0m $EACHSYSFILE"
                        mv ${SYSCONFLICTIONPATH}${EACHSYSFILE} $SYSBUSDES
                    done
                    ls ${SYSCONFCONFLICTIONPATH} | while read EACHSYSCONFFILE; do
                        echo -e "\e[1mkare: \e[31m测试11: \e[0m $EACHSYSCONFFILE"
                        mv ${SYSCONFCONFLICTIONPATH}${EACHSYSCONFFILE} $SYSCONFDES
                    done
                    ls ${SYSCONFCONFLICTIONPATH_} | while read EACHSYSCONFFILE_; do
                        echo -e "\e[1mkare: \e[31m测试12: \e[0m ${EACHSYSCONFFILE_}"
                        mv ${SYSCONFCONFLICTIONPATH_}${EACHSYSCONFFILE_} ${SYSCONFDES_}
                    done
                fi
            fi
        fi
    fi
    python3 "$EXEDIR/rmclient.py" "${containerTypeValue}" "${containerNameValue}" "$1"

    desktopFile=$(dpkg -c $1 | grep -o '/usr/share/applications/.*\.desktop')
    # desktopNameList=
    # SRVFLAG=0
    # [ -z "${desktopFile}" ] && SRVFLAG=1

    # iconFileList=$(dpkg -c "$1" | egrep -i '/usr/share/icons|/usr/share/.*/icons|/usr/share/pixmaps' | egrep '*.png$|*.svg$|*.xpm$' | awk '!/^l/ {print $NF}')
    # iconFileListLn=$(dpkg -c "$1" | egrep -i '/usr/share/icons|/usr/share/.*/icons|/usr/share/pixmaps' | egrep '*.png$|*.svg$|*.xpm$' | awk -F '[0-2][0-9]:[0-9][0-9] ' '/^l/{ print $2 }')
    # if [ ${SRVFLAG} -eq 0 ] && [ -z "${iconFileList}" ]; then
    #     iconFileList=$(dpkg -c "$1" | egrep -i '/usr/share/' | egrep '*.png$|*.svg$|*.xpm$' | awk '!/^l/ {print $NF}')
    #     iconFileListLn=$(dpkg -c "$1" | egrep -i '/usr/share/' | egrep '*.png$|*.svg$|*.xpm$' | awk -F '[0-2][0-9]:[0-9][0-9] ' '/^l/{ print $2 }')
    # fi
    # for eachIconFile in ${iconFileList}; do
    #     eachIconDir=${eachIconFile%/*}
    #     [ ! -d "${vpWS}/vp/${eachIconDir}" ] && mkdir -p ${vpWS}/vp/${eachIconDir}
    # done
    # while read eachIconFileLn; do
    #     [ -z "${eachIconFileLn}" ] && break
    #     eachIconFile=$(echo ${eachIconFileLn} | awk -F ' -> ' '{ print $1 }')
    #     eachIconDir=${eachIconFile%/*}
    #     [ ! -d "${vpWS}/vp/${eachIconDir}" ] && mkdir -p ${vpWS}/vp/${eachIconDir}
    # done <<<"${iconFileListLn}"
    # htmlFileList=$(dpkg -c "$1" | egrep -i '.*\.html' | awk -F' ' '{ print $NF }')
    # for eachHtmlFile in ${htmlFileList}; do
    #     eachHtmlDir=${eachHtmlFile%/*}
    #     [ ! -d "${vpWS}/vp/${eachHtmlDir}" ] && mkdir -p ${vpWS}/vp/${eachHtmlDir}
    # done
    # TODO
    if [ ${containerTypeValue} == "bwrap" ]; then
        DEB_NAME="$1"
        SESSION_DBUS_SRV=$(dpkg -c "${DEB_NAME}" | grep "/usr/share/dbus-1/services/" | egrep ".service$" | awk '!/^l/ {print $NF}')
        SYSTEM_DBUS_SRV=$(dpkg -c "${DEB_NAME}" | grep "/usr/share/dbus-1/system-services/" | egrep ".service$" | awk '!/^l/ {print $NF}')
        SYSTEM_DBUS_CONF=$(dpkg -c "${DEB_NAME}" | grep "/etc/dbus-1/system.d/" | egrep ".conf$" | awk '!/^l/ {print $NF}')

        for EACHSESSRV in ${SESSION_DBUS_SRV}; do
            SESSRVDIR=${EACHSESSRV%/*}
            [ ! -d "${vpWS}/vp/${SESSRVDIR}" ] && mkdir -p ${vpWS}/vp/${SESSRVDIR}
        done
        for EACHSYSSRV in ${SYSTEM_DBUS_SRV}; do
            SYSSRVDIR=${EACHSYSSRV%/*}
            [ ! -d "${vpWS}/vp/${SYSSRVDIR}" ] && mkdir -p ${vpWS}/vp/${SYSSRVDIR}
        done
        for EACHSYSCONF in ${SYSTEM_DBUS_CONF}; do
            SYSCONFDIR=${EACHSYSCONF%/*}
            [ ! -d "${vpWS}/vp/${SYSCONFDIR}" ] && mkdir -p ${vpWS}/vp/${SYSCONFDIR}
        done
    fi
    # DONE
    # for eachIconFile in ${iconFileList}; do
    #     eachIconDir=${eachIconFile%/*}
    #     if [ ${containerTypeValue} == "docker" ]; then
    #         $containerTypeValue cp ${containerNameValue}:/${eachIconFile} ${vpWS}/vp/${eachIconDir}
    #     elif [ ${containerTypeValue} == "bwrap" ]; then
    #         $containerTypeValue $BWRAP_OPTIONS cp /${eachIconFile} ${vpWS}/vp/${eachIconDir}
    #     fi
    # done
    # # DONE
    # for eachHtmlFile in ${htmlFileList}; do
    #     eachHtmlDir=${eachHtmlFile%/*}
    #     if [ ${containerTypeValue} == "docker" ]; then
    #         $containerTypeValue cp ${containerNameValue}:/${eachHtmlFile} ${vpWS}/vp/${eachHtmlDir}
    #     elif [ ${containerTypeValue} == "bwrap" ]; then
    #         $containerTypeValue $BWRAP_OPTIONS cp /${eachHtmlFile} ${vpWS}/vp/${eachHtmlDir}
    #     fi
    # done
    # # TODU
    # while read eachIconFileLn; do
    #     [ -z "${eachIconFileLn}" ] && break
    #     read lnIconFile destIconFile < <(echo ${eachIconFileLn} | awk -F ' -> ' '{ print $1, $2 }')
    #     lnIconDir=${lnIconFile%/*}
    #     cp -rf ${vpWS}/vp/${lnIconDir}/${destIconFile} ${vpWS}/vp/${lnIconFile}
    # done <<<"${iconFileListLn}"

    link_desktop_file=
    # 处理desktop文件是链接文件的情况
    if [ ${containerTypeValue} == "docker" ]; then
        search_link_file=$("$containerTypeValue" exec "$containerNameValue" test -L "$desktopFile"  && echo "true" || echo "false")
        if [ "$search_link_file" = "true" ]; then
            original_desktop_file=$("$containerTypeValue" exec "$containerNameValue" readlink -f "$desktopFile")
            $containerTypeValue exec --user root "$containerNameValue" rm -f $desktopFile
            $containerTypeValue exec --user root "$containerNameValue" cp -f $original_desktop_file /usr/share/applications
        fi
    fi
    # 判断安装目录中是否存在/etc/xdg/autostart/*.desktop文件
    autostartFile=$(dpkg -c $1 | grep -o '/etc/xdg/autostart/.*\.desktop')
    # desktopDirDest='/opt/compatibility_layer/vpws/vp/usr/share/applications'
    # boringcmd=()
    # compensation=1
    desktopNameList=
    for eachDesktopFile in ${desktopFile} ${autostartFile}; do
        desktopNameTmp=${eachDesktopFile##*/}
        desktopNameList="${desktopNameList} ${desktopNameTmp}"
        # eachDesktopDir=${eachDesktopFile%/*}
        # [ ! -d "${vpWS}/vp/${eachDesktopDir}" ] && mkdir -p "${vpWS}/vp/${eachDesktopDir}"
        # if [ ${containerTypeValue} == "docker" ]; then
        #     $containerTypeValue cp $containerNameValue:$eachDesktopFile ${vpWS}/vp/${eachDesktopDir}
        # elif [ ${containerTypeValue} == "bwrap" ]; then
        #     $containerTypeValue $BWRAP_OPTIONS cp $eachDesktopFile ${vpWS}/vp/${eachDesktopDir}
        # fi
        # eachDesktopFile="/opt/compatibility_layer/vpws/vp${eachDesktopFile}"
        # sed -i 's/\r$//' $eachDesktopFile
        # scriptName="kare run"
        # execSegment=$(grep -m 1 '^Exec=' ${eachDesktopFile} | sed 's/^Exec=//')
        # iconSegment=$(grep -m 1 '^Icon=' ${eachDesktopFile} | sed 's/^Icon=//')
        # placeholder=$(echo $execSegment | egrep -o "%[a-zA-Z]")
        # cpre=$(echo $execSegment | egrep -o "^(\/usr\/bin\/bash -c |\/bin\/bash -c |bash -c |sh -c |\/bin\/sh -c |\/usr\/bin\/sh -c)")
        # execSegmentDropPlaceholder=${execSegment% \%[a-zA-Z]}
        # [ ! -z "${placeholder}" ] && execSegmentDropPlaceholder=$(echo $execSegmentDropPlaceholder | sed -r "s/( \-[a-zA-Z])$//")
        # [ ! -z "$cpre" ] && execSegmentDropPlaceholder=$(echo $execSegmentDropPlaceholder | sed -r "s/(^$cpre)//")
        # execTmp1=$(echo $execSegment | sed -r 's/^(\/usr\/bin\/bash -c |\/bin\/bash -c |bash -c |sh -c |\/bin\/sh -c |\/usr\/bin\/sh -c)//')
        # execTmp1=$(echo $execTmp1 | sed -r 's/^(\/usr\/bin\/bash |\/bin\/bash |bash |sh |\/bin\/sh |\/usr\/bin\/sh )//')
        # execTmp2=${execTmp1% \%[a-zA-Z]}
        # execCmd=${execTmp2%% *}
        # [ ${execCmd: -1} = "\\" ] && execCmd=${execCmd%?}

        # if [[ "$execCmd" =~ \"* ]] || [[ "$execCmd" =~ \'* ]]; then
        #     execCmd=$(echo "$execCmd" | tr -d "'\"")
        # fi

        # if [[ "$execCmd" =~ "xdg-open" ]] ||
        #     [[ "$execCmd" =~ "gvfs-open" ]] ||
        #     [[ "$execCmd" =~ "gio open" ]]; then
        #     continue
        # fi

        # execAidDir="/usr/bin"
        # if [[ "${execCmd}" != "/"* ]]; then
        #     execCmd="/usr/bin/$execCmd"
        # else
        #     execAidDir=${execCmd%/*}
        # fi

        # command -v "$execCmd" >/dev/null && execCmd="/usr/bin/${containerNameValue}" && execAidDir=/usr/bin
        # echo "$execCmd" | grep -q '=' && execCmd="/usr/bin/${containerNameValue}" && execAidDir=/usr/bin
        # [[ "${boringcmd[@]}" =~ "${execCmd}" ]] && execCmd=${execCmd}${compensation}
        # boringcmd[${compensation}]=${execCmd}
        # ((compensation++))
        # if [ -f "$execCmd" ]; then
        #     read -t 5 -p "系统中已存在同名可执行文件,是否替换为本次安装的软件(Y/N)?" userInput
        #     userInput=${userInput:-"Y"}
        #     if [ ${userInput,,} = "y" ]; then
        #         if [ -e "${execCmd}_OLD" ]; then
        #             mv "${execCmd}" "${execCmd}_OLDx"
        #         else
        #             mv "${execCmd}" "${execCmd}_OLD"
        #         fi
        #         if [ ! -d "${vpWS}/vp${execAidDir}" ]; then
        #             mkdir -p ${vpWS}/vp${execAidDir}
        #         fi
        #         touch ${vpWS}/vp${execCmd}
        #         echo "#!/bin/bash" >${vpWS}/vp${execCmd}
        #         chmod a+x ${vpWS}/vp${execCmd}
        #         if [ ! -z "${placeholder}" ]; then
        #             echo "$scriptName ${softwareNameValue}_${softwareVersionNum} ${execSegmentDropPlaceholder} \$@" >>${vpWS}/vp${execCmd}
        #         else
        #             echo "$scriptName ${softwareNameValue}_${softwareVersionNum} ${execSegmentDropPlaceholder}" >>${vpWS}/vp${execCmd}
        #         fi
        #         if [ -d "/sysroot" ]; then
        #             sed -i "s|^Exec=.*|Exec=/opt/kare${execCmd} ${placeholder}|g" $eachDesktopFile
        #             if [[ "$iconSegment" == "/"* ]]; then
        #                 sed -i "s|^Icon=.*|Icon=/opt/kare${iconSegment}|g" $eachDesktopFile
        #             fi
        #         else
        #             sed -i "s|^Exec=.*|Exec=${execCmd} ${placeholder}|g" $eachDesktopFile
        #         fi
        #         sed -i "s|^DBusActivatable=true|#DBusActivatable=true|" $eachDesktopFile
        #         sed -i "s|^TryExec=|#TryExec=|" $eachDesktopFile
        #         echo "替换完成, 系统原有执行文件被命名为${execCmd}_OLD*" | tee -a $logFile
        #     else
        #         echo "您的选择是不替换，软件启动将以原有软件的方式进行启动" | tee -a $logFile
        #     fi
        # else
        #     [ ! -d "${vpWS}/vp${execAidDir}" ] && mkdir -p ${vpWS}/vp${execAidDir}
        #     touch ${vpWS}/vp${execCmd}
        #     echo "#!/bin/bash" >${vpWS}/vp${execCmd}
        #     chmod a+x ${vpWS}/vp${execCmd}
        #     if [ ! -z "${placeholder}" ]; then
        #         echo "$scriptName ${softwareNameValue}_${softwareVersionNum} ${execSegmentDropPlaceholder} \$@" >>${vpWS}/vp${execCmd}
        #     else
        #         echo "$scriptName ${softwareNameValue}_${softwareVersionNum} ${execSegmentDropPlaceholder}" >>${vpWS}/vp${execCmd}
        #     fi
        #     if [ -d "/sysroot" ]; then
        #         sed -i "s|^Exec=.*|Exec=/opt/kare${execCmd} ${placeholder}|g" $eachDesktopFile
        #         if [[ "$iconSegment" == "/"* ]]; then
        #             sed -i "s|^Icon=.*|Icon=/opt/kare${iconSegment}|g" $eachDesktopFile
        #         fi
        #     else
        #         sed -i "s|^Exec=.*|Exec=${execCmd} ${placeholder}|g" $eachDesktopFile
        #     fi
        #     sed -i "s|^DBusActivatable=true|#DBusActivatable=true|" $eachDesktopFile
        #     sed -i "s|^TryExec=|#TryExec=|" $eachDesktopFile
        # fi
    done

    # serviceRegistration $1
    SYSTEM_SERVICE_LIST=$(python3 "$EXEDIR/srvsignclient.py" "docker" "$containerNameValue" "$1" "$BWRAP_OPTIONS")

    if [ ${containerTypeValue} == "bwrap" ]; then
        for EACHSESSRV in ${SESSION_DBUS_SRV}; do
            SESSRVDIR=${EACHSESSRV%/*}
            if [ ${containerTypeValue} == "docker" ]; then
                $containerTypeValue cp $containerNameValue:/$EACHSESSRV ${vpWS}/vp/${SESSRVDIR}
            elif [ ${containerTypeValue} == "bwrap" ]; then
                $containerTypeValue $BWRAP_OPTIONS cp /$EACHSESSRV ${vpWS}/vp/${SESSRVDIR}
            fi
            SRVCMD=$(grep -m 1 '^Exec=' ${vpWS}/vp/${EACHSESSRV} | sed 's|^Exec=||')
            sed -i "s|^Exec=|#Exec=|" ${vpWS}/vp/${EACHSESSRV}
            echo "Exec=$SRV_LAUNCH_SCRIPT ${softwareNameValue}_${softwareVersionNum}" >>${vpWS}/vp/${EACHSESSRV}
        done
        [ ! -z "${SRVCMD}" ] && [ ${SRVFLAG} -eq 1 ] && configtool_kare "set" $CONFIGFILE "Exec" "${softwareNameValue}_${softwareVersionNum}" "${SRVCMD}"

        SRVCMD=
        for EACHSYSSRV in ${SYSTEM_DBUS_SRV}; do
            SYSSRVDIR=${EACHSYSSRV%/*}
            if [ ${containerTypeValue} == "docker" ]; then
                $containerTypeValue cp $containerNameValue:/$EACHSYSSRV ${vpWS}/vp/${SYSSRVDIR}
            elif [ ${containerTypeValue} == "bwrap" ]; then
                $containerTypeValue $BWRAP_OPTIONS cp /$EACHSYSSRV ${vpWS}/vp/${SYSSRVDIR}
            fi
            SRVCMD=$(grep -m 1 '^Exec=' ${vpWS}/vp/${EACHSYSSRV} | sed 's|^Exec=||')
            sed -i "s|^Exec=|#Exec=|" ${vpWS}/vp/${EACHSYSSRV}
            echo "Exec=$SRV_LAUNCH_SCRIPT ${softwareNameValue}_${softwareVersionNum}" >>${vpWS}/vp/${EACHSYSSRV}
        done
        [ ! -z "${SRVCMD}" ] && [ ${SRVFLAG} -eq 1 ] && configtool_kare "set" $CONFIGFILE "Exec" "${softwareNameValue}_${softwareVersionNum}" "${SRVCMD}"

        for EACHSYSCONF in ${SYSTEM_DBUS_CONF}; do
            SYSCONFDIR=${EACHSYSCONF%/*}
            if [ ${containerTypeValue} == "docker" ]; then
                $containerTypeValue cp $containerNameValue:/$EACHSYSCONF ${vpWS}/vp/${SYSCONFDIR}
            elif [ ${containerTypeValue} == "bwrap" ]; then
                $containerTypeValue $BWRAP_OPTIONS cp /$EACHSYSCONF ${vpWS}/vp/${SYSCONFDIR}
            fi
        done
    fi
    # 根据系统判断包管理方式
    desktopNameList=$(echo $desktopNameList | sed 's/^[ ]*//g')
    if [ -d "/sysroot" ]; then
        kareManager "$softwareNameValue" "$softwareVersionNum" "$softwareArch"     # 不可变系统
    else
        python3 "$EXEDIR/vpclient.py" "$softwareNameValue" "$softwareVersionNum" "$softwareArch" "$desktopNameList"
        vpManager "$softwareNameValue" "$softwareVersionNum" "$softwareArch" "$desktopNameList"
    fi
    
    if [ ${containerTypeValue} == "docker" ]; then
        ! grep -q "$softwareNameValue=$softwareVersionNum" $INSTALLLIST && echo "$softwareNameValue=$softwareVersionNum=$RTE" >>$INSTALLLIST
        [ $containerNameValue = "v10sp1Driver" ] && ! grep -q $softwareNameValue $DriverInstallList &>/dev/null && echo "${softwareNameValue}=v10sp1Driver" >>$DriverInstallList
    elif [ ${containerTypeValue} == "bwrap" ]; then
        ! grep -q "$softwareNameValue=$softwareVersionNum" $INSTALLLIST && echo "$softwareNameValue=$softwareVersionNum "DIR=$ENVDIR"" >>$INSTALLLIST
    fi
    python3 "$EXEDIR/postclient.py" "$softwareNameValue" 
    [ ! -z "${TMPFILE}" ] && rm "${TMPFILE}" &>/dev/null
}

function listFun() {
    printf "%-39s%-39s%14s\n" "软件包名" "软件包版本号" "运行环境" | tee -a $logFile
    echo "==================================" "==================================" "=============" | tee -a $logFile
    [ -e $INSTALLLIST ] && cat $INSTALLLIST | awk -F '=| DIR=' '{printf "%-35s%-35s%-35s\n",$1,$2,$3}' | tee -a $logFile
}

function list_installation_files() {
    shift
    package_name="$1"
    packages=()
    # 从 install.list 文件中读取每一行，并将 packageName 添加到数组中
    while IFS='=' read -r packageName _; do
        packages+=("$packageName")
    done < $INSTALLLIST

    found=false
    for package in "${packages[@]}"; do
        if [[ "$package" == "$package_name" ]]; then
            found=true
            break
        fi
    done

    if $found; then
        if [ -d "/sysroot" ]; then
            cat /opt/compatibility_layer/vpws/kare_manager_${package_name}_* 2>/dev/null
        else
            dpkg -L "$package_name"
        fi
    else
        echo -e "\e[1mkare-query: \e[0m软件包 ${package_name} 没有被安装"
    fi
}

function search_package() {
    shift
    search_content="$1"
    search_dir="${vpWS}"
    if [ -d "/sysroot" ]; then
        search_result=$(grep -r "$search_content" "${search_dir}" 2>/dev/null)
        if [[ -n "$search_result" ]]; then
            for eachline in ${search_result}; do
                search_file=$(echo "$eachline" | cut -d: -f1)
                search_path=$(echo "$eachline" | cut -d: -f2)
                package_name=$(echo "$search_file" | awk -F"/" '{print $NF}' | cut -d_ -f3)
                if [ ! -z "${package_name}" ] && [ ! -z "${search_path}" ]; then
                    echo "$package_name: $search_path"
                fi
            done
        else
            search_result2=$(grep -r "$search_content" "${vpWS_BAK1}" 2>/dev/null)
            if [[ -n "$search_result2" ]]; then
                for eachline in ${search_result2}; do
                    search_file=$(echo "$eachline" | cut -d: -f1)
                    search_path=$(echo "$eachline" | cut -d: -f2)
                    package_name=$(echo "$search_file" | awk -F"/" '{print $NF}' | cut -d_ -f3)
                    if [ ! -z "${package_name}" ] && [ ! -z "${search_path}" ]; then
                        echo "$package_name: $search_path"
                    fi
                done
            else
                echo -e "\e[1mkare-query: \e[0m没有找到与 *${search_content}* 相匹配的路径"
            fi
        fi
    else
        dpkg -S "$search_content"
    fi
 }

install_packages() {
    shift
    while [ $# -gt 0 ]; do
        deb_file="$1"
        if [[ "$deb_file" != *".deb" ]]; then
            shift
            continue
        fi
        if [[ "$deb_file" != "/"* ]]; then
            deb_file=$(pwd)"/"$deb_file""
        fi
        if [[ "${deb_file}" =~ [[:space:]] ]]; then
            cp -p "${deb_file}" /tmp/
            deb_file="/tmp/$(basename "${deb_file}")"
            TMPFILE="${deb_file}"
        fi
        splitSoftwareDeb $deb_file
        local aRes=$(Abandon "$deb_file")
        if [ "$aRes" -eq -1 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m宿主系统上已安装同名软件, 请手动卸载后再安装本应用" | tee -a $logFile
            echo -e "若卸载后安装本应用,可能会打破系统原有软件包之间的依赖关系,请谨慎操作" | tee -a $logFile
        elif [ "$aRes" -eq -2 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m同名软件已存在于其他兼容环境, 请手动卸载后再安装本应用" | tee -a $logFile
            echo -e "若卸载后安装本应用,可能会打破系统原有软件包之间的依赖关系,请谨慎操作" | tee -a $logFile
        elif [ "$aRes" -eq 0 ]; then
            installFun "$deb_file"
        elif [ "$aRes" -eq 1 ]; then
            RichL "$deb_file"
        fi
        shift
    done
}

function removeFun() {
    localSoftwareDebName="$1"
    localSoftwareDebVersionNum="$2"
    if [ ${containerTypeValue} == "docker" ]; then
        LocalContainerName=$($containerTypeValue ps -a | grep -wo "${localSoftwareDebName}_${localSoftwareDebVersionNum}" | awk '{print $NF}')
        if [ -z "$LocalContainerName" ]; then
            echo "${localSoftwareDebName}_${localSoftwareDebVersionNum} 在系统上不存在,程序退出" | tee -a $logFile
            exit -1
        fi
        $containerTypeValue rm -f "$LocalContainerName" >/dev/null
        umountOverlay $LocalContainerName

    elif [ ${containerTypeValue} == "bwrap" ]; then
        # bwrap卸载逻辑"
        if grep -q "$localSoftwareDebName=$localSoftwareDebVersionNum" "$INSTALLLIST"; then
            INSTALL_DIR=$(grep "^$localSoftwareDebName=" "$INSTALLLIST" | cut -d' ' -f2 | awk -F'=' '{print $2}')
            if [[ -n "$INSTALL_DIR" ]]; then
                echo "软件包当前安装路径为：$INSTALL_DIR" >>$logFile
                getBwrapOption $INSTALL_DIR
                sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS apt remove -y $localSoftwareDebName=$localSoftwareDebVersionNum
            else
                echo "软件包 $localSoftwareDebName 不存在或者缺少DIR的值" | tee -a $logFile
            fi
        else
            echo "${localSoftwareDebName}_${localSoftwareDebVersionNum} 在系统上不存在,程序退出" | tee -a $logFile
            exit -1
        fi
    fi
    # 在install.list中移除
    sed -i "/$localSoftwareDebName=$localSoftwareDebVersionNum/d" $INSTALLLIST
    # 删除安装文件
    if [ -d "/sysroot" ]; then
        file_list="/opt/compatibility_layer/vpws/kare_manager_${localSoftwareDebName}_${localSoftwareDebVersionNum}"
        while IFS= read -r file; do
            if [[ $file == *".desktop" ]]; then
                desktop=${file##*/}
                find_result=$(find /home/*/桌面/ -type f -name "$desktop")
                if [ ! -z "$find_result" ]; then
                    for each in $find_result; do
                            rm "$each" 2>/dev/null
                    done
                fi
            fi
            rm "$file" 2>/dev/null
        done < "$file_list"
        rm "$file_list"
    else
        if dpkg -l | grep "${localSoftwareDebName}" | grep -q "${localSoftwareDebVersionNum}-kare"; then
            dpkg -P "${localSoftwareDebName}" 2>/dev/null
        fi
    fi
    echo "软件包-"${localSoftwareDebName}_${localSoftwareDebVersionNum}" 卸载完成" | tee -a $logFile
}

function removeFunP() {
    if [ ${containerTypeValue} == "docker" ]; then
        while [ $# -gt 0 ]; do
            localSoftwareDebName="$1"
            LocalContainerName=$($containerTypeValue ps -a | grep -o "$localSoftwareDebName[^ ]*")
            if [ -z "$LocalContainerName" ]; then
                if ! grep -q $localSoftwareDebName $DriverInstallList &>/dev/null; then
                    echo ""$localSoftwareDebName" 在系统上不存在,程序退出" | tee -a $logFile
                    exit -1
                else
                    ServerName=$(grep $localSoftwareDebName $DriverInstallList | sed "s/$localSoftwareDebName=//")
                    [ ! -z "$ServerName" ] && $containerTypeValue exec -u root $ServerName apt purge $localSoftwareDebName -y
                    if [ -d "/sysroot" ]; then
                        localSoftwareVersionNum=$(grep $localSoftwareDebName $INSTALLLIST | awk -F"=" '{print $2}')
                        file_list="/opt/compatibility_layer/vpws/kare_manager_${localSoftwareDebName}_${localSoftwareVersionNum}"
                        while IFS= read -r file; do
                        if [[ $file == *".desktop" ]]; then
                                desktop=${file##*/}
                                find_result=$(find /home/*/桌面/ -type f -name "$desktop")
                                if [ ! -z "$find_result" ]; then
                                    for each in $find_result; do
                                            rm "$each" 2>/dev/null
                                    done
                                fi
                            fi
                            rm "$file" 2>/dev/null
                        done < "$file_list"
                        rm "$file_list"
                    else
                        if dpkg -l | grep "${localSoftwareDebName}" | grep -q "kare"; then
                            dpkg -P "${localSoftwareDebName}" 2>/dev/null
                        fi
                    fi
                    sed -i "/$localSoftwareDebName/d" $INSTALLLIST
                    sed -i "/$localSoftwareDebName/d" $DriverInstallList
                fi
                # echo ""$localSoftwareDebName" 在系统上不存在,程序退出" | tee -a $logFile
                # exit -1
            fi
            $containerTypeValue ps -a | grep -o "$localSoftwareDebName[^ ]*" | while read line; do
                localSoftwareNameValue=${line%_*}
                localSoftwareVersionNum=${line##*_}
                if [ -z $line ]; then
                    echo "Null"
                    continue
                fi
                $containerTypeValue rm -f "$line" >/dev/null
                sed -i "/$localSoftwareNameValue=$localSoftwareVersionNum/d" $INSTALLLIST
                if [ -d "/sysroot" ]; then
                    umountOverlay $line
                    file_list="/opt/compatibility_layer/vpws/kare_manager_${localSoftwareNameValue}_${localSoftwareVersionNum}"
                    while IFS= read -r file; do
                       if [[ $file == *".desktop" ]]; then
                            desktop=${file##*/}
                            find_result=$(find /home/*/桌面/ -type f -name "$desktop")
                            if [ ! -z "$find_result" ]; then
                                for each in $find_result; do
                                        rm "$each" 2>/dev/null
                                done
                            fi
                        fi
                        rm "$file" 2>/dev/null
                    done < "$file_list"
                    rm "$file_list"
                    [ -f "${vpWS_BAK1}/kare_manager_${containerNameValue}" ] && rm "${vpWS_BAK1}/kare_manager_${containerNameValue}" &>/dev/null
                else
                    if dpkg -l | grep "${localSoftwareNameValue}" | grep -q "${localSoftwareVersionNum}-kare"; then
                        sudo dpkg -P "${localSoftwareDebName}" 2>/dev/null
                    fi
                fi
                echo "${localSoftwareNameValue}_${localSoftwareVersionNum} 卸载完成" | tee -a $logFile
            done
            shift
        done
    elif [ ${containerTypeValue} == "bwrap" ]; then
        # bwrap卸载逻辑"
        while [ $# -gt 0 ]; do
            localSoftwareDebName="$1"
            if grep -q "^$localSoftwareDebName=" "$INSTALLLIST"; then
                PACKAGE_VERSION=$(grep "^$localSoftwareDebName=" "$INSTALLLIST" | awk -F'=' '{print $2}' | awk '{print $1}')
                INSTALL_DIR=$(grep "^$localSoftwareDebName=" "$INSTALLLIST" | awk -F'DIR=' '{print $2}')
                if [[ -n "$INSTALL_DIR" ]]; then
                    echo "软件包当前安装路径为：$INSTALL_DIR" >>$logFile
                    getBwrapOption $INSTALL_DIR
                    sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS apt remove -y $localSoftwareDebName=$PACKAGE_VERSION

                    sed -i "/$localSoftwareDebName=$PACKAGE_VERSION/d" $INSTALLLIST
                    configtool_kare "del" $CONFIGFILE "Exec" "${localSoftwareDebName}_${PACKAGE_VERSION}"
                    if dpkg -l | grep "${localSoftwareDebName}" | grep -q "${PACKAGE_VERSION}-kare"; then
                        dpkg -P "${localSoftwareDebName}" 2>/dev/null
                    fi
                    echo "${localSoftwareDebName}_${PACKAGE_VERSION} 卸载完成" | tee -a $logFile
                    shift
                else
                    echo "软件包 $localSoftwareDebName 不存在或者缺少DIR的值" | tee -a $logFile
                    exit -1
                fi
            else
                echo "${localSoftwareDebName} 在系统上不存在,程序退出" | tee -a $logFile
                exit -1
            fi
        done
    fi
}

# 服务注册
# function serviceRegistration() {
#     # 提取service文件
#     systemd_file=$(dpkg-deb -c "$1" | awk '/\/etc\/systemd\/system|\/lib\/systemd\/system|\/usr\/lib\/systemd\/system|\/etc\/systemd\/user|\/usr\/lib\/systemd\/user|\/lib\/systemd\/user/ && !/\/$/ {sub(/^\./, "", $NF); print $NF}')

#     # 检查service_file是否为空
#     if [[ -z "$systemd_file" ]]; then
#         return # 跳出当前函数
#     else
#         for file in $systemd_file; do
#             directory=$(dirname "$file")
#             [ ! -d "${vpWS}/vp${directory}" ] && mkdir -p "${vpWS}/vp${directory}"
#             if [ ${containerTypeValue} == "docker" ]; then
#                 $containerTypeValue cp $containerNameValue:$file ${vpWS}/vp${directory}
#             elif [ ${containerTypeValue} == "bwrap" ]; then
#                 sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS cp $file ${vpWS}/vp${directory}
#             fi

#             if [[ $file =~ \.service$ ]]; then
#                 # 判断是否包含After字段
#                 if grep -q "^After" "${vpWS}/vp$file"; then
#                     sed -i '/^After/ s/$/ docker.service/' "${vpWS}/vp$file"
#                 else
#                     sed -i '/^Description/ a\After=docker.service' "${vpWS}/vp$file"
#                 fi
#                 # 判断是否包含Exec字段
#                 if grep -q "^Exec" "${vpWS}/vp$file"; then
#                     matches_line=$(grep -e '^Exec[^=]*=.*' "${vpWS}/vp$file")

#                     while IFS= read -r line; do
#                         # 获取当前Exec字段及其内容，
#                         exec_field=${line%%=*}
#                         original_value="${line#*=}"

#                         # 组成新的字段内容
#                         modification_value="/usr/bin/kare run $containerNameValue $original_value"

#                         # 注释当前行并生成新行
#                         new_line="$exec_field=$modification_value"
#                         sed -i "s|^$line|# $line\n$new_line|" "${vpWS}/vp$file"
#                     done <<<"$matches_line"
#                 fi
#             fi
#         done
#     fi
# }

# function cpServiceFile() {
#     # 提取service文件
#     systemd_file=$(dpkg-deb -c "$1" | awk '/\/etc\/systemd\/system|\/lib\/systemd\/system|\/usr\/lib\/systemd\/system|\/etc\/systemd\/user|\/usr\/lib\/systemd\/user|\/lib\/systemd\/user/ && !/\/$/ {sub(/^\./, "", $NF); print $NF}')

#     # 检查service_file是否为空
#     if [[ -z "$systemd_file" ]]; then
#         return # 跳出当前函数
#     else
#         if [ -d "/sysroot" ]; then
#             unpack_path="/var/opt/kare/unpack_${containerNameValue}"
#         else
#             unpack_path="/tmp/unpack_${containerNameValue}"
#         fi
#         dpkg -X "$1" "$unpack_path" > /dev/null #解压到指定文件夹

#         system_service_files=$(find "$unpack_path/etc/systemd/system"  "$unpack_path/lib/systemd/system" "$unpack_path/usr/lib/systemd/system" -type f 2>/dev/null | xargs)
#         user_service_files=$(find "$unpack_path/etc/systemd/user"  "$unpack_path/lib/systemd/user" "$unpack_path/usr/lib/systemd/user"  -type f 2>/dev/null | xargs)

#         if [[ -n "$system_service_files" ]]; then
#             for file in $system_service_files; do
#                 file_path=$(echo "$file" | sed "s|$unpack_path||")
#                 immutable_file_path=/var/opt/kare/${file_path}
#                 SERVICE_NAME=$(basename "$file_path")
#                 SYSTEM_SERVICE_LIST+=("$SERVICE_NAME")
#                 if [ -f $file_path ] || [ -f $immutable_file_path ]; then
#                     echo "该服务文件在系统中存在同名文件,继续安装" >> $logFile
#                     continue
#                 fi

#                 # 判断是否包含After字段
#                 if grep -q "^After" "$file"; then
#                     sed -i '/^After/ s/$/ docker.service/' "$file"
#                 else
#                     sed -i '/^Description/ a\After=docker.service' "$file"
#                 fi

#                 # 判断是否包含Exec字段
#                 if grep -q "^Exec" "$file"; then
#                     matches_line=$(grep -e '^Exec[^=]*=.*' "$file")

#                     while IFS= read -r line; do
#                         # 获取当前Exec字段及其内容，
#                         exec_field=${line%%=*}
#                         original_value="${line#*=}"

#                         # 组成新的字段内容
#                         modification_value="/usr/bin/kare run $containerNameValue $original_value"

#                         # 注释当前行并生成新行
#                         new_line="$exec_field=$modification_value"
#                         sed -i "s|^$line|# $line\n$new_line|" "$file"
#                     done <<<"$matches_line"
#                 fi
                
#                 # 复制文件到目标路径
#                 directory=$(dirname "$file_path")
#                 if [ -d "/sysroot" ]; then
#                     install_path=/var/opt/kare${directory}
#                     cp "$file" "$install_path"
#                     echo "Copied $file to $install_path" >> $logFile
#                 else
#                     cp "$file" "$directory"
#                     echo "Copied $file to $directory" >> $logFile
#                 fi
#             done <<< "$system_service_files"
#         fi

#         if [[ -n "$user_service_files" ]]; then
#             for file in $user_service_files; do
#                 file_path=$(echo "$file" | sed "s|$unpack_path||")
#                 immutable_file_path=/var/opt/kare/${file_path}
#                 SERVICE_NAME=$(basename "$file_path")
#                 USER_SERVICE_LIST+=("$SERVICE_NAME")
#                 if [ -f $file_path ] || [ -f $immutable_file_path ]; then
#                     echo "该服务文件在系统中存在同名文件,继续安装" >> $logFile
#                     continue
#                 fi

#                 # 判断是否包含After字段
#                 if grep -q "^After" "$file"; then
#                     sed -i '/^After/ s/$/ docker.service/' "$file"
#                 else
#                     sed -i '/^Description/ a\After=docker.service' "$file"
#                 fi

#                 # 判断是否包含Exec字段
#                 if grep -q "^Exec" "$file"; then
#                     matches_line=$(grep -e '^Exec[^=]*=.*' "$file")

#                     while IFS= read -r line; do
#                         # 获取当前Exec字段及其内容，
#                         exec_field=${line%%=*}
#                         original_value="${line#*=}"

#                         # 组成新的字段内容
#                         modification_value="/usr/bin/kare run $containerNameValue $original_value"

#                         # 注释当前行并生成新行
#                         new_line="$exec_field=$modification_value"
#                         sed -i "s|^$line|# $line\n$new_line|" "$file"
#                     done <<<"$matches_line"
#                 fi
#                 # 复制文件到目标路径
#                 directory=$(dirname "$file_path")
#                 if [ -d "/sysroot" ]; then
#                     install_path=/var/opt/kare${directory}
#                     cp "$file" "$install_path"
#                     echo "Copied $file to $install_path" >> $logFile
#                 else
#                     cp "$file" "$directory"
#                     echo "Copied $file to $directory" >> $logFile
#                 fi
#             done <<< "$user_service_files"
#         fi
#         rm -rf "$unpack_path"
#     fi
# }

function listBuildEnv() {
    ENVKEY=$(dbus-send --system --type=method_call --print-reply \
        --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentImages |
        sed -r '/^("|<none>)/d' | awk 'NR>=3&&NF>0{print $1}' | cut -d_ -f2)
    for eachkey in $ENVKEY; do
        case $eachkey in
        u16)
            echo ubuntu16.04
            ;;
        u18)
            echo ubuntu18.04
            ;;
        u20)
            echo ubuntu20.04
            ;;
        u22)
            echo ubuntu22.04
            ;;
        u24)
            echo ubuntu24.04
            ;;
        ok1)
            echo openkylin1.0
            ;;
        ok2)
            echo openkylin2.0
            ;;
        *)
            echo $eachkey
            ;;
        esac
    done
}

function runFun() {
    Exec="$@"
    Exec=${Exec#"kare run "}
    case $(echo ${Exec} | awk -F " " '{print $1}') in
    bash*)
        Exec=${Exec#"bash "}
        ;;
    /bin/bash*)
        Exec=${Exec#"/bin/bash "}
        ;;
    /usr/bin/bash*)
        Exec=${Exec#"/usr/bin/bash "}
        ;;
    sh*)
        Exec=${Exec#"sh "}
        ;;
    /bin/sh*)
        Exec=${Exec#"/bin/sh "}
        ;;
    /usr/bin/sh*)
        Exec=${Exec#"/usr/bin/sh "}
        ;;
    *) ;;
    esac
    if [[ "$Exec" =~ "RichR" ]] || [[ "$Exec" = *"rightclick" ]]; then
        /bin/bash /usr/bin/runWithCompatibility.sh "$Exec"
        exit 0
    fi

    RECE="$@"
    echo "kare run "${RECE}"" | tee -a $logFile
    local CName=${1}
    local CMDANDPARAM=$(echo $RECE | sed "s/${CName} //")
    # local VALIDEXEC=$(echo ${CMDANDPARAM} | sed -r 's/^(\/usr\/bin\/bash |\/bin\/bash |bash |sh |\/bin\/sh |\/usr\/bin\/sh )//')

    debName="${CName}"
    debExec="${CMDANDPARAM}"
    DISPLAYVAL="${DISPLAY:-0}"
    CURUID=
    while read userpath; do
    if dbus-send --system --print-reply \
        --dest=org.freedesktop.login1 "${userpath}" org.freedesktop.DBus.Properties.Get string:org.freedesktop.login1.User string:State |
        grep -wq "active"; then
        CURUID=$(echo ${userpath##*_})
    fi
    done < <(dbus-send --system --type=method_call --print-reply \
            --dest=org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager.ListUsers |
            grep "object path" | sed 's/object path//g;s/ *//g;s/"//g')

    if [ ${containerTypeValue} == "docker" ]; then
        legalFlag=$(dbus-send --system --type=method_call --print-reply \
            --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentPs |
            grep -o "$debName[^ ]*")
        if [ -z "$legalFlag" ]; then
            echo "ERROR - 系统上不存在${debName}软件包,可通过kare -l查看存在的软件包及版本号" | tee -a $logFile
            exit -1
        fi
        dbus-send --system --type=method_call --print-reply \
            --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentPs |
            grep -o "$debName[^ ]*" | while read eachContainer; do
            replyValue=$(dbus-send --system --type=method_call --print-reply \
                --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentStart \
                string:"$eachContainer" | awk -F " " 'NR==2 { print $NF }')
            if [ $replyValue -ne 0 ]; then
                echo "ERROR - 容器 $eachContainer 启动失败" | tee -a $logFile
                exit -1
            fi
            # 执行ldconfig 解决有些库的链接可能会失效的问题
            ret=$(dbus-send --system --type=method_call --print-reply \
                    --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentRun \
                            string:"$eachContainer" string:"${CURUID:-1000}" string:"echo qwer1234 | sudo -S ldconfig" | awk -F " " 'NR==2 { print $NF }')
            if [ $ret -eq 0 ]; then
                echo "DEBUG - running ldconfig success" | tee -a $logFile
            else
                echo "ERROR - running ldconfig failed" | tee -a $logFile
            fi
            # 启动session和system类型的dbus-daemon-proxy 
            test_exit=$(dbus-send --system --type=method_call --print-reply \
                --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentExec \
                       string:"$eachContainer" string:"test -x '/usr/bin/dbus-daemon-proxy'" | awk -F " " 'NR==2 { print $NF }')
            if [ $test_exit -eq 0 ]; then
                echo "activate dbus-daemon-proxy" | tee -a $logFile
                ret=$(dbus-send --system --type=method_call --print-reply \
                        --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentRun \
                               string:"$eachContainer" string:"${CURUID:-1000}" string:"DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus /usr/bin/dbus-daemon-proxy --verbose --session --port ${SESPORT} --namespace ${debName%%_*}" | awk -F " " 'NR==2 { print $NF }')
                if [ $ret -eq 0 ]; then
                    echo "dbus-daemon-proxy(session) start  success" | tee -a $logFile
                else
                    echo "ERROR - dbus-daemon-proxy(session) start failed" | tee -a $logFile
                fi
                ret=$(dbus-send --system --type=method_call --print-reply \
                        --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentRun \
                               string:"$eachContainer" string:"${CURUID:-1000}" string:"echo qwer1234 | sudo -S /usr/bin/dbus-daemon-proxy --verbose --system --port ${SYSPORT} --namespace ${debName%%_*}" | awk -F " " 'NR==2 { print $NF }')
                if [ $ret -eq 0 ]; then
                    echo "dbus-daemon-proxy(system) start success" | tee -a $logFile
                else
                    echo "ERROR - dbus-daemon-proxy(system) start failed" | tee -a $logFile
                fi
            fi

            exec=$(echo $debExec | awk '{print $1}')
            isTerminal=0
            runPath="~"
            desktopFiles=""
	        curDesktopFile=""
            if [ -d "/sysroot" ]; then
                desktopFiles=$(cat /opt/compatibility_layer/vpws/kare_manager_${debName%%_*}_* |  grep -o '/opt/kare/usr/share/applications/.*\.desktop')
            else 
                debFiles=$(find /opt/compatibility_layer/vpws -type f -name "${debName%%_*}_*.deb")
                desktopFiles=$(dpkg -c ${debFiles} | grep -o '/usr/share/applications/.*\.desktop')
            fi
            for eachDesktopFile in ${desktopFiles}; do
                execSegment=$(grep -m 1 '^Exec=' ${eachDesktopFile} | sed -e 's/^Exec=//' |  sed -r "s/( %[a-zA-Z])$//")
                terminal=$(grep -m 1 '^Terminal=true' ${eachDesktopFile})
                pathSegment=$(grep -m 1 '^#Path=' ${eachDesktopFile} | sed -e 's/^#Path=//')
                if [[ -n "$execSegment" && -n "$terminal" ]];then
                    if [ "${#execSegment}" -gt 0 ] && [ "${execSegment: -1}" = " " ]; then
                        execSegment="${execSegment% }"
                    fi
                    execCmd=$(awk '!/^#/ {print $4}' "${execSegment}")
                    execCmd=$(echo $execCmd | sed "s/['\"]//g")
                    exec=$(echo $exec | sed "s/['\"]//g")
                    if [[ "$execCmd" = "$exec" ]]; then
                        isTerminal=1
                    fi
                fi

                if [ "${#pathSegment}" -gt 0 ];then
                    execCmd=$(awk '!/^#/ {print $4}' "${execSegment}")
                    execCmd=$(echo $execCmd | sed "s/['\"]//g")
                    exec=$(echo $exec | sed "s/['\"]//g")
                    if [[ "$execCmd" = "$exec" ]]; then
                        runPath=${pathSegment}
                    fi
                fi
                execCmd=$(awk '!/^#/ {print $4}' "${execSegment}")
                execCmd=$(echo $execCmd | sed "s/['\"]//g")
                exec=$(echo $exec | sed "s/['\"]//g")
		        if [[ "$execCmd" = "$exec" ]]; then
                   curDesktopFile=${eachDesktopFile}
                fi
            done

            procDir="/tmp/kare-proc"
            [ ! -d ${procDir} ] && mkdir -p ${procDir}

            if [ ${isTerminal} -eq 1 ]; then
                echo "Terminal"
                dbus-send --system --type=method_call --print-reply \
                    --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentExecTerminal \
                    string:"$eachContainer" string:"${CURUID:-1000}" string:"cd $runPath;DISPLAY=${DISPLAYVAL};mate-terminal -e '$debExec'" | tee -a $logFile
            elif [ "$isCommandLineApplication" = "true" ]; then
                dbus-send --system --type=method_call --print-reply \
                    --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentPidRun \
                    string:"$eachContainer" string:"${CURUID:-1000}" string:"cd $runPath;DISPLAY=${DISPLAYVAL};env PANSHI_APP_DESKTOP=$curDesktopFile $debExec" string:"$token"| tee -a $logFile
            else
                echo "No Terminal"

                dbus-send --system --type=method_call --print-reply \
                    --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentRun \
                    string:"$eachContainer" string:"${CURUID:-1000}" string:"cd $runPath;DISPLAY=${DISPLAYVAL};env PANSHI_APP_DESKTOP=$curDesktopFile $debExec" | tee -a $logFile
            fi

            containerId=$(dbus-send --system --type=method_call --print-reply \
                    --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentPs | grep -i "$eachContainer" |  grep -v 'grep' | awk '{print $1}')
            dockerRunId=$(ps -ef | grep "$containerId" | grep -v 'grep' | awk '{print $2}')
            find_child_processes "$dockerRunId"
            printf "%s\n" "${child_pids[@]}" > ${procDir}/${eachContainer}_pid

        done
    elif [ ${containerTypeValue} == "bwrap" ]; then
        # bwrap运行逻辑"
        packageName=${debName%_*}
        if grep -q "^$packageName=" "$INSTALLLIST"; then
            PACKAGE_VERSION=$(grep "^$packageName=" "$INSTALLLIST" | awk -F'=' '{print $2}' | awk '{print $1}')
            INSTALL_DIR=$(grep "^$packageName=" "$INSTALLLIST" | awk -F'DIR=' '{print $2}')
            if [[ -n "$INSTALL_DIR" ]]; then
                echo "软件包当前安装路径为：$INSTALL_DIR" >>$logFile
                getBwrapOption $INSTALL_DIR
                /usr/bin/bwrap  $BWRAP_OPTIONS --setenv XDG_RUNTIME_DIR /run/user/1000 "$debExec" 2>"$errorLogFile"
                if [[ $? -eq 0 ]]; then
                    echo "程序运行成功" >>$logFile
                else
                    echo "程序运行失败，错误信息：" | tee -a $logFile
                    cat "$errorLogFile" | tee -a $logFile
                fi
            else
                echo "软件包 $packageName 不存在或者缺少DIR的值" | tee -a $logFile
            fi
        else
            echo "ERROR - 系统上不存在${debName}软件包,可通过kare -l查看存在的软件包及版本号" | tee -a $logFile
        fi
    fi
}

function find_child_processes() {
    local parent_pid=$1
    local pids=$(ps -e -o ppid,pid,cmd | awk -v parent_pid="$parent_pid" '!/dbus-daemon-proxy/ && $NF != "/bin/bash" && $1 == parent_pid { print $2 }')

    for pid in $pids; do
        child_pids+=($pid)
        find_child_processes "$pid"
    done
}

function buildEnv() {
    /usr/bin/build-env.sh $1
    exit $?
}

function checkOptionE() {
    if [ ${containerTypeValue} == "docker" ]; then
        $containerTypeValue images | grep $containerImage >/dev/null 2>&1
        if [ $? -ne 0 ]; then
            echo "ERROR - 环境 $1 不存在,请首先通过 sudo kare -b 构建基础环境(可能比较耗时)" | tee -a $logFile
            exit -1
        fi
    else
        echo "checkOptionE::containerTypeValue:bwrap"
    fi
}

function getBusList() {
    [ ! -d ${SESBUSPATH} ] && mkdir -p ${SESBUSPATH}
    [ ! -d ${SYSBUSPATH} ] && mkdir -p ${SYSBUSPATH}
    [ ! -d ${GSETTINGSPATH} ] && mkdir -p ${GSETTINGSPATH}
    [ ! -d ${SYSCONFPATH} ] && mkdir -p ${SYSCONFPATH}
    [ ! -d ${SYSCONFPATH_} ] && mkdir -p ${SYSCONFPATH_}
    [ ! -d ${SESCONFLICTIONPATH} ] && mkdir -p ${SESCONFLICTIONPATH}
    [ ! -d ${SYSCONFLICTIONPATH} ] && mkdir -p ${SYSCONFLICTIONPATH}
    [ ! -d ${SYSCONFCONFLICTIONPATH} ] && mkdir -p ${SYSCONFCONFLICTIONPATH}
    [ ! -d ${SYSCONFCONFLICTIONPATH_} ] && mkdir -p ${SYSCONFCONFLICTIONPATH_}
    if [ -d "${ENVDIR}/usr/share/dbus-1/services" ]; then
        ls ${ENVDIR}/usr/share/dbus-1/services >${SESBUSPATH}/sesbus.list
    fi
    if [ -d "${ENVDIR}/usr/share/dbus-1/system-services" ]; then
        ls ${ENVDIR}/usr/share/dbus-1/system-services >${SYSBUSPATH}/sysbus.list
    fi
    if [ -d "/usr/share/glib-2.0/schemas" ]; then
        ls /usr/share/glib-2.0/schemas >${GSETTINGSPATH}/gsettings.list
    fi
    if [ -d "${ENVDIR}/etc/dbus-1/system.d" ]; then
        ls ${ENVDIR}/etc/dbus-1/system.d >${SYSCONFPATH}/sysconf.list
    fi
    if [ -d "${ENVDIR}/usr/share/dbus-1/system.d/" ]; then
        ls ${ENVDIR}/usr/share/dbus-1/system.d/ >${SYSCONFPATH_}/sysconf_.list
    fi
    : >${SESBUSPATH}/sesbus.diff
    : >${SESBUSPATH}/sesbus.same
    : >${SYSBUSPATH}/sysbus.diff
    : >${SYSBUSPATH}/sysbus.same
    : >${SYSCONFPATH}/sysconf.diff
    : >${SYSCONFPATH}/sysconf.same
    : >${SYSCONFPATH_}/sysconf_.diff
    : >${SYSCONFPATH_}/sysconf_.same
    [ ! -f "${GSETTINGSPATH}/gsettings.diff" ] && touch ${GSETTINGSPATH}/gsettings.diff
}

function kareManager() {    
    echo $1 $2
    find "/opt/compatibility_layer/vpws/vp" -type f -o -type l | while read -r file; do
        opt_file_path=${file//\/opt\/compatibility_layer\/vpws\/vp/\/opt\/kare}
        opt_file_dir=$(dirname "$opt_file_path")
        if [ ! -d "$opt_file_dir" ]; then
            mkdir -p "$opt_file_dir"
        fi
        if [[ "$file" == *"etc"* ]]; then
            etc_file_path=${file//\/opt\/compatibility_layer\/vpws\/vp/}
            cp "$file" "$etc_file_path"
            echo "$etc_file_path" >> /opt/compatibility_layer/vpws/kare_manager_"$1"_"$2"
        elif [[ "$file" == *"/usr/share/dbus-1/system-services/"* ]]; then
            install_service_file_path=${file//\/opt\/compatibility_layer\/vpws\/vp/\/opt\/kare}
            cp "$file" "$install_service_file_path"
            echo "${file//\/opt\/compatibility_layer\/vpws\/vp//}" >> /opt/compatibility_layer/vpws/kare_manager_"$1"_"$2"
            cp "$file" "${install_service_file_path//\/opt\/kare\/usr\/share\/dbus-1\/system-services\//\/opt\/kare\/usr\/share\/}"
            echo "${install_service_file_path//\/opt\/kare\/usr\/share\/dbus-1\/system-services\//\/opt\/kare\/usr\/share\/}" >> /opt/compatibility_layer/vpws/kare_manager_"$1"_"$2"
        else
            cp -d "$file" "${file//\/opt\/compatibility_layer\/vpws\/vp/\/opt\/kare}"
            file_type=$(file "$file")
            if [[ "$file_type" == *"shell script"* ]]; then
                kysec_set -n exectl -v verified  "${file//\/opt\/compatibility_layer\/vpws\/vp/\/opt\/kare}" > /dev/null 2>&1
            fi
            echo "${file//\/opt\/compatibility_layer\/vpws\/vp/\/opt\/kare}" >> /opt/compatibility_layer/vpws/kare_manager_"$1"_"$2"
        fi
    done
    # rm -rf /opt/compatibility_layer/vpws/vp
    update-desktop-database /opt/kare/usr/share/applications
    SYSTEM_SERVICE_LIST=$(echo ${SYSTEM_SERVICE_LIST} | sed -r "s/(None|'|\[|\]|,)//g")
    for service in ${SYSTEM_SERVICE_LIST}; do
        systemctl daemon-reload
        systemctl enable "${service}"
        systemctl restart "${service}"
    done

 }

function vpManager() {
    echo "正在设置 KARE 软件包管理 ..."
    pkgName="$1"
    karePkgName="$1"
    pkgVersion="${2}-kare"
    pkgVersionDropKare="${2}"
    archValue="$3"
    desktopValue="$4"
    cd $vpWS
    if ! (fuser /var/lib/dpkg/lock-frontend && fuser /var/lib/dpkg/lock) >/dev/null 2>&1; then
        sudo dpkg -i --force-overwrite ${pkgName}_${pkgVersion}_${archValue}.deb
        if [ $? -ne 0 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m所安装的软件包不满足依赖关系,软件包安装失败" | tee -a $logFile
            apt purge -y ${pkgName} &>/dev/null &
            $containerTypeValue rm -f $containerNameValue &>/dev/null
            umountOverlay $containerNameValue &>/dev/null
            exit -1
        fi
    else
        count=120
        while (fuser /var/lib/dpkg/lock-frontend || fuser /var/lib/dpkg/lock); do
            echo "dpkg被占用,正在等待获取缓存锁...最长等待剩余时间${count}s" | tee -a $logFile
            sleep 1
            ((count--))
            [ $count -le 0 ] && break
        done
        sudo dpkg -i --force-overwrite ${pkgName}_${pkgVersion}_${archValue}.deb
        if [ $? -ne 0 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m所安装的软件包不满足依赖关系,软件包安装失败" | tee -a $logFile
            apt purge -y ${pkgName} &>/dev/null &
            $containerTypeValue rm -f $containerNameValue &>/dev/null
            umountOverlay $containerNameValue &>/dev/null
            exit -1
        fi
    fi
    [ $? -ne 0 ] && echo "ERROR - VP Config Failed" >>$logFile
    cd - >/dev/null
    for x in $vpWS/vp/*; do
        if [ $x != "$vpWS/vp/DEBIAN" ]; then
            echo 11
        fi
    done

    SYSTEM_SERVICE_LIST=$(echo ${SYSTEM_SERVICE_LIST} | sed -r "s/(None|'|\[|\]|,)//g")
    for service in ${SYSTEM_SERVICE_LIST}; do
        systemctl daemon-reload
        systemctl enable "${service}"
        systemctl restart "${service}"
    done
    
}

function fixDepends(){

    localSoftwareDebName="$1"
    LocalContainerName=$($containerTypeValue ps -a | grep -o "$localSoftwareDebName[^ ]*")
    if [ -z "$LocalContainerName" ]; then
        echo ""$localSoftwareDebName" 在系统上不存在,程序退出" | tee -a $logFile
        exit -1
    fi
    docker start $LocalContainerName
    docker exec -it -u root $LocalContainerName /bin/bash -c "/usr/bin/python3 /usr/bin/check_depends.py $1"
    # docker exec -it -u root $LocalContainerName /bin/bash -c "/usr/bin/python3 $EXEDIR/fixdependclient.py $1"

}

function inspectFun(){
    local appName="$1"
    local container_name=$(dbus-send --system --type=method_call --print-reply \
            --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentPs | awk '{print $NF}' |
            grep "$appName[^ ]*")
    if [ -z "${container_name}" ]; then
        if grep -qE "^$appName=" $DriverInstallList &>/dev/null; then
            container_name=$(grep $appName $DriverInstallList | sed "s/$appName=//")
        else
            echo "ERROR - 应用 $appName 不存在" | tee -a $logFile
            exit -1
        fi
    fi
    echo "DEBUG - kare inspect $container_name" >>$logFile
    $containerTypeValue start $container_name >>$logFile 2>&1
    if [ $? -ne 0 ]; then
        echo "ERROR - 容器 $container_name 启动失败" | tee -a $logFile
        exit -1
    fi
    $containerTypeValue exec -it "$container_name" bash
}

function main() {
    while getopts ":e:t:i:r:P:lhEb:L:S:f:p:" opt; do
        case $opt in
        i)
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            install_packages "$@"
            exit 0
            ;;
        t)
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            softwareTypeValue=$OPTARG
            ;;
        r)
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            removeFun "${@:2}"
            exit 0
            ;;
        P)
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            removeFunP "${@:2}"
            exit 0
            ;;
        l)
            listFun
            exit 0
            ;;
        L)
            list_installation_files "$@"
            exit 0
            ;;
        S)
            search_package "$@"
            exit 0
            ;;
        p)
            isCommandLineApplication=true
            token=$OPTARG
            ;;
        e)
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            OPTARG=${OPTARG,,}
            case ${OPTARG,,} in
            ubuntu16.04)
                RTE="ubuntu16.04"
                ENVDIR=$ENVDIRPRE"u16"
                containerImage=$containerImagePre"u16"
                ;;
            ubuntu18.04)
                RTE="ubuntu18.04"
                ENVDIR=$ENVDIRPRE"u18"
                containerImage=$containerImagePre"u18"
                ;;
            ubuntu20.04)
                RTE="ubuntu20.04"
                ENVDIR=$ENVDIRPRE"u20"
                containerImage=$containerImagePre"u20"
                ;;
            ubuntu22.04)
                RTE="ubuntu22.04"
                ENVDIR=$ENVDIRPRE"u22"
                containerImage=$containerImagePre"u22"
                ;;
            ubuntu24.04)
                RTE="ubuntu24.04"
                ENVDIR=$ENVDIRPRE"u24"
                containerImage=$containerImagePre"u24"
                ;;
            openkylin1.0)
                RTE="openkylin1.0"
                ENVDIR=$ENVDIRPRE"ok1"
                containerImage=$containerImagePre"ok1"
                ;;
            openkylin2.0)
                RTE="openkylin2.0"
                ENVDIR=$ENVDIRPRE"ok2"
                containerImage=$containerImagePre"ok2"
                ;;
            v4)
                RTE="v4"
                ENVDIR=$ENVDIRPRE"v4"
                containerImage=$containerImagePre"v4"
                ;;
            v10)
                RTE="v10"
                ENVDIR=$ENVDIRPRE"v10"
                containerImage=$containerImagePre"v10"
                ;;
            v10sp1)
                RTE="v10sp1"
                ENVDIR=$ENVDIRPRE"v10sp1"
                containerImage=$containerImagePre"v10sp1"
                ;;
            shadow)
                RTE="shadow"
                ENVDIR=$ENVDIRPRE"shadow"
                containerImage=$containerImagePre"shadow"
                ;;
            *)
                echo -e "\e[1mkare: \e[31m错误: \e[0m-e 输入参数错误,可选选项:"
                printf "%-20s%-20s%-20s%-20s\n" "ubuntu16.04" "ubuntu18.04" "ubuntu20.04" "ubuntu22.04" "ubuntu24.04"
                printf "%-20s%-20s%-20s\n" "v4" "v10" "v10sp1"
                printf "%-20s%-20s\n" "openkylin1.0" "openkylin2.0"
                exit -1
                ;;
            esac
            checkOptionE $OPTARG
            getBusList
            getBwrapOption $ENVDIR
            [ $? -ne 0 ] && exit -1
            ;;
        E)
            listBuildEnv
            exit 0
            ;;
        b)
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            case ${OPTARG,,} in
            ubuntu16.04)
                buildEnv kare-u16
                ;;
            ubuntu18.04)
                buildEnv kare-u18
                ;;
            ubuntu20.04)
                buildEnv kare-u20
                ;;
            ubuntu22.04)
                buildEnv kare-u22
                ;;
            ubuntu24.04)
                buildEnv kare-u24
                ;;
            openkylin1.0)
                buildEnv kare-ok1
                ;;
            openkylin2.0)
                buildEnv kare-ok2
            ;;
            v10)
                buildEnv kare-v10
                ;;
            v10sp1)
                buildEnv kare-v10sp1
                ;;
            shadow)
                buildEnv kare-shadow
                ;;
            local)
                buildEnv local
                ;;
            *)
                echo -e "\e[1mkare: \e[31m错误: \e[0m-b 输入参数错误,可选选项:"
                printf "%-20s%-20s%-20s%-20s\n" "ubuntu16.04" "ubuntu18.04" "ubuntu20.04" "ubuntu22.04" "ubuntu24.04"
                printf "%-20s%-20s%-20s\n" "v4" "v10" "v10sp1" "shadow"
                printf "%-20s%-20s\n" "openkylin1.0" "openkylin2.0"
                printf "%-20s%-20s\n" "local"
                exit -1
                ;;
            esac
            exit 0
            ;;
        h)
            printUsage
            exit 0
            ;;
        f)
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            fixDepends "${@:2}"
            exit 0
            ;;
        :)
            echo -e "\e[31m选项 -$OPTARG 后面需要一个参数值\e[0m"
            printUsage
            exit -1
            ;;
        ?)
            echo "无效的选项 -$OPTARG"
            printUsage
            exit 1
            ;;
        esac
    done

    # 处理其他命令
    shift $((OPTIND - 1))
    if [ "$#" -eq 0 ]; then
        printUsage
        exit -1
    elif [ "$1" == "run" ]; then
        runFun "${@:2}"
    elif [ "$1" == "install" ]; then
        if [ $(id -u) -ne 0 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
            exit -1
        fi
        install_packages "${@:1}"
    elif [ "$1" == "remove" ]; then
        if [ $(id -u) -ne 0 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
            exit -1
        fi
        removeFun "${@:2}"
    elif [ "$1" == "list" ]; then
        listFun
    elif [ "$1" == "inspect" ]; then
        if [ $(id -u) -ne 0 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
            exit -1
        fi
        inspectFun "${@:2}"
    else
        echo "命令无效"
        printUsage
        exit 1
    fi
}

main "$@"
