#!/bin/bash

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'
CONFIGFILE="$CONFIGDIR/configure.ini"
INSTALLLIST="$CONFIGDIR/install.list"

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"
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/
KAREHOST=$(cat /etc/os-release | grep PRETTY_NAME)

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\n" "" "ubuntu16.04" "ubuntu18.04" "ubuntu20.04" "ubuntu22.04"
    printf "%-21s%-20s%-20s%-20s\n" "" "v4" "v10" "v10sp1"
    printf "%-21s%-20s%-20s\n" "" "openkylin1.0" "openkylin2.0"
    echo "  -b <参数>          构建兼容运行环境"
    printf "%-21s%-20s%-20s%-20s%-20s\n" "" "ubuntu16.04" "ubuntu18.04" "ubuntu20.04" "ubuntu22.04"
    printf "%-21s%-20s%-20s%-20s\n" "" "v4" "v10" "v10sp1"
    printf "%-21s%-20s%-20s\n" "" "openkylin1.0" "openkylin2.0"
    echo "  -E                 列出构建完成的兼容运行环境"
    echo "  -i|install <参数>  安装软件包"
    echo "  -r|remove  <参数>  精确移除软件包(包名 包版本)"
    echo "  -P <参数>          模糊移除软件包(包名)"
    echo "  -l|list            列出已安装的软件包"
    echo "  -L <参数>          列出软件包的已安装文件"
    echo "  -S <参数>          列出文件所在软件包及路径"
    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 -E"
    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=""
function splitSoftwareDeb() {
        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')
        containerNameValue=${softwareNameValue}_${softwareVersionNum}
}

# 获取 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

    OK2KAREDIRS=(
        bin
        lib
        lib64
        sbin
        var
        usr
    )
    for DIR in "${OK2KAREDIRS[@]}"; do
        fuser -mk /var/kare/$1/merged/$DIR
    done
    for DIR in "${OK2KAREDIRS[@]}"; do
        umount -fl /var/kare/$1/merged/$DIR
    done
    for DIR in "${OK2KAREDIRS[@]}"; do
        rm -rf /var/kare/$1/merged/$DIR /var/kare/$1/overlay/upper/$DIR /var/kare/$1/overlay/work/$DIR  >/dev/null 2>&1
    done
}

# 容器操作
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() {
    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" ]; then
        containerEnv="-e WAYLAND_DISPLAY= \
-e QT_X11_NO_MITSHM=1 \
-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}"
    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}"
    fi

    # 容器特殊参数
    containerSpecialParam=""
    # 容器登录用户
    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"
    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
            containerSharedDir=$containerSharedDir" -v $each:$each"
        elif [ $each == "/opt" ]; then
            containerSharedDir=$containerSharedDir" -v $each/compatibility_layer/config/bus/:$each/compatibility_layer/config/bus/"
            # 必要目录挂载完毕，寻找是否有自建目录
        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" ]; then
        OK2KAREDIRS=(
            bin
            lib
            lib64
            sbin
            var
            usr
        )
        # 构建overlay
        for DIR in "${OK2KAREDIRS[@]}"; do
            [ ! -d "/var/kare/$containerNameValue/overlay/upper/$DIR" ] && mkdir -p "/var/kare/$containerNameValue/overlay/upper/$DIR"
            [ ! -d "/var/kare/$containerNameValue/overlay/work/$DIR" ] && mkdir -p "/var/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=/var/kare/$containerNameValue/overlay/upper/$DIR,workdir=/var/kare/$containerNameValue/overlay/work/$DIR /var/kare/$containerNameValue/merged/$DIR
            containerSharedDir=$containerSharedDir" -v /var/kare/$containerNameValue/merged/$DIR:/$DIR"
        done
        mv /var/kare/$containerNameValue/merged/usr/bin/systemctl /var/kare/$containerNameValue/merged/usr/bin/systemctl-off
        cp /var/kare/$containerNameValue/merged/bin/true -p /var/kare/$containerNameValue/merged/usr/bin/systemctl
        containerCreateCmd="$containerTypeValue create --privileged --ipc host -u 1000 -it --name $containerNameValue $containerEnv $containerSharedDir $containerImage"
    else 
        containerCreateCmd="$containerTypeValue create --privileged --ipc host -u 1000 -it --name $containerNameValue $containerEnv $containerSharedDir $containerImage"
    fi
    # 创建容器
    # containerCreateCmd="$containerTypeValue create --privileged -u 1000 -it --name $containerNameValue $containerEnv $containerSharedDir $containerImage"
    echo "DEBUG - 容器创建命令: $containerCreateCmd" >>$logFile
    $containerCreateCmd >>$logFile 2>&1
    if [ $? -eq 0 ]; then
        echo "DEBUG - 容器${containerNameValue}创建成功" >>$logFile
    else
        echo "ERROR - 容器${containerNameValue}创建失败" >>$logFile
        return -1
    fi
}

containerImagePre="baseimage_"
containerImage="baseimage_v10"
iconFileList=
iconFileListLn=
RichLF=0
function Abandon() {
    if dpkg -l | awk '$0 ~ /^ii/{print $2}' | grep -xq ${softwareNameValue}; then
        if ! grep $softwareNameValue $INSTALLLIST &>/dev/null; then
            echo -1
            return
        fi
        if [ $(grep $softwareNameValue $INSTALLLIST | awk -F= '{print $3}') != "$RTE" ]; then
            echo -2
            return
        fi
        RichLF=1
        echo 1
        return
    fi
    echo 0
    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
    if [ ${containerTypeValue} == "docker" ]; then
        echo "DEBUG - 软件包-$1 对应的容器名称为-$containerNameValue 软件包名称为-$softwareNameValue 版本号为-$softwareVersionNum" >>$logFile
            createContainer "$1"
            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
                    return -1
                fi
                echo "ERROR - 容器创建失败导致软件包安装失败,请检查软件包名是否符合规范后重新安装" | tee -a $logFile
                $containerTypeValue rm -f $containerNameValue &>/dev/null
                umountOverlay $containerNameValue
                return -1
            fi
			if [ "$containerImage" != "baseimage_ok2" ];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
                    return -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
                    return -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
                    return -1
                fi
			fi
            $containerTypeValue start $containerNameValue >>$logFile 2>&1
			if [ "$containerImage" = "baseimage_ok2" ];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/
            fi
            if [ $? -ne 0 ]; then
                echo "ERROR - 容器$containerNameValue启动失败" >>$logFile
                echo "ERROR - 容器启动失败,详细原因请查看${logFile},解决问题后请重新安装" | tee -a $logFile
                $containerTypeValue rm -f $containerNameValue >/dev/null
                umountOverlay $containerNameValue
                exit -1
            else
                echo "DEBUG - 容器$containerNameValue启动成功" >>$logFile
            fi

            if [ "$containerImage" = "baseimage_ok2" ];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
            fi

            pipestatus=("${PIPESTATUS[@]}")
            if [ "${pipestatus[0]}" -eq 0 ]; then
                echo "DEBUG - 软件包$1安装成功" >>$logFile
            else
                echo "ERROR - 软件包$1安装失败" | tee -a $logFile
                $containerTypeValue rm -f $containerNameValue >/dev/null
                umountOverlay $containerNameValue
                exit -1
            fi
            $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

            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 "\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}
                $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 "\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}
                $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}" >>${SYSBUSPATH}/sysconf.same
                else
                ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && echo "${EACHCONF}" >>${SYSBUSPATH}/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}" >>${SYSBUSPATH}/sysconf_.same
                else
                ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf_.diff && echo "${EACHCONF}" >>${SYSBUSPATH}/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" ];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" ];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 "\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
                    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}" >>${SYSBUSPATH}/sysconf.same
            else
            ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && echo "${EACHCONF}" >>${SYSBUSPATH}/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}" >>${SYSBUSPATH}/sysconf_.same
            else
            ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf_.diff && echo "${EACHCONF}" >>${SYSBUSPATH}/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" ];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" ];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
                fi
            fi
        fi
    fi

    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
    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

    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
    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
    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}"

    # 判断安装目录中是否存在/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
    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
        [[ "${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 $vpWS

    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
        vpManager "$softwareNameValue" "$softwareVersionNum" "$softwareArch" "$desktopNameList"
    fi
    
    if [ ${containerTypeValue} == "docker" ]; then
        ! grep -q "$softwareNameValue=$softwareVersionNum" $INSTALLLIST && echo "$softwareNameValue=$softwareVersionNum=$RTE" >>$INSTALLLIST
    elif [ ${containerTypeValue} == "bwrap" ]; then
        ! grep -q "$softwareNameValue=$softwareVersionNum" $INSTALLLIST && echo "$softwareNameValue=$softwareVersionNum "DIR=$ENVDIR"" >>$INSTALLLIST
    fi
}

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}_*
        else
            dpkg -L "$package_name"
        fi
    else
        echo "软件包 $package_name 未安装."
    fi
}

function search_package() {
    shift
    search_content="$1"
    search_dir=/opt/compatibility_layer/vpws
    if [ -d "/sysroot" ]; then
        if [ "$(ls -A "$search_dir")" ]; then  
            if cd "$search_dir"; then  
                search_result=$(grep -r "$search_content" .)  
                if [[ -n "$search_result" ]]; then
                    search_file=$(echo "$search_result" | cut -d: -f1)  
                    search_path=$(echo "$search_result" | cut -d: -f2)
                    package_name=$(echo "$search_file" | awk -F'_' '{print $3}')
                    echo "$package_name:$search_path"
                else  
                    echo "没有找到与 *$search_content* 相匹配的路径"
                fi  
            else  
                echo "没有找到与 *$search_content* 相匹配的路径"  
            fi
        else  
            echo "没有找到与 *$search_content* 相匹配的路径"
        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
        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
                    done
                fi
            fi
            rm "$file"
        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
                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
                                done
                            fi
                        fi
                        rm "$file"
                    done < "$file_list"
                    rm "$file_list"
                else
                    if dpkg -l | grep "${localSoftwareNameValue}" | grep -q "${localSoftwareVersionNum}-kare"; then
                        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文件
    service_file=$(dpkg -c "$1" | awk '$NF ~ /\.service$/ && $NF !~ /^\.\/usr\/share\/dbus-1/ && !/^l/ { sub(/^\.\//, "/", $NF); print $NF }')
    link_service_file=$(dpkg -c "$1" | awk '$NF ~ /\.service$/ && /^l/ { print $6 }' | sed 's/\.//')

    # 检查service_file是否为空
    if [[ -z "$service_file" ]]; then
        return # 跳出当前函数
    else
        for file in $service_file $link_service_file; do
            if [ -f $file ]; then
                echo "该服务文件在系统中存在同名文件，安装终止"
                if [ ${containerTypeValue} == "docker" ]; then
                    $containerTypeValue rm -f $containerNameValue >/dev/null
                elif [ ${containerTypeValue} == "bwrap" ]; then
                    sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS apt remove $softwareNameValue=$softwareVersionNum
                fi
                exit -1
            fi
            directory=$(dirname "$file")
            [ ! -d "${vpWS}/vp${directory}" ] && mkdir -p "${vpWS}/vp${directory}"
            if [ ${containerTypeValue} == "docker" ]; then
                $containerTypeValue cp $containerNameValue:$file $2/vp${directory}
            elif [ ${containerTypeValue} == "bwrap" ]; then
                sudo /usr/bin/bwrap --uid 0 --gid 0 $BWRAP_OPTIONS cp $file $2/vp${directory}
            fi
            # 判断是否包含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
        done
    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
            ;;
        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} //g")
    local VALIDEXEC=$(echo ${CMDANDPARAM} | sed -r 's/^(\/usr\/bin\/bash |\/bin\/bash |bash |sh |\/bin\/sh |\/usr\/bin\/sh )//')

    debName="${CName}"
    debExec="${VALIDEXEC}"

    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
            # 启动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:"$debName" 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:"$debName" string:"DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus /usr/bin/dbus-daemon-proxy --verbose --session --port ${SESPORT} --namespace $debExec" | 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:"$debName" string:"echo qwer1234 | sudo -S /usr/bin/dbus-daemon-proxy --verbose --system --port ${SYSPORT} --namespace $debExec" | 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
            debFiles=$(find /opt/compatibility_layer/vpws -type f -name "${debName%%_*}*.deb")
            echo  $debName $debFiles
            desktopFiles=$(dpkg -c ${debFiles} | grep -o '/usr/share/applications/.*\.desktop')
            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})
                if [[ -n "$execSegment" && -n "$terminal" ]];then
                    execCmd=$(awk '/^kare/ {print $4}' ${execSegment})
                    if [ "$execCmd" = "$exec" ]; then
                        isTerminal=1
                    fi
                fi
            done

            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:"$debExec" | 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:"$debExec" | tee -a $logFile
            fi


        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 buildEnv() {
    /usr/bin/build-env.sh $1
    exit 0
}

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 ${SESCONFLICTIONPATH} ] && mkdir -p ${SESCONFLICTIONPATH}
    [ ! -d ${SYSCONFLICTIONPATH} ] && mkdir -p ${SYSCONFLICTIONPATH}
    [ ! -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 | 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
            cp "$file" "${file/\/opt\/compatibility_layer\/vpws\/vp/}"
            echo ${file/\/opt\/compatibility_layer\/vpws\/vp/} >> /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 $file ${file//\/opt\/compatibility_layer\/vpws\/vp/\/opt\/kare}
            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
 }

function vpManager() {
    echo "正在设置 KARE 软件包管理 ..."
    pkgName="$1"
    karePkgName="$1"
    pkgVersion="${2}-kare"
    pkgVersionDropKare="${2}"
    archValue="$3"
    desktopValue="$4"
    [ ! -d $vpWS ] && mkdir -p $vpWS/vp/DEBIAN
    # if [ ! -f $vpControlFile -o ! -f $vpPostRmFile ]; then
        # echo "WARNING - VP File Not Exists" >>$logFile
        echo -e 'Package: 
Version: 
Architecture: 
Maintainer: zhanglin <zhanglin@kylinos.cn>
Installed-Size: 160
Depends: kare
Section: misc
Priority: optional
Description: virtual package.' >$vpControlFile

        echo -e '#!/bin/bash

pkgName=
pkgVersion=
desktopName=

DesktopPath=/home/*/Desktop
SYSLANG=$(export | grep -w LANG)
if [[ "${SYSLANG}" =~ "zh_CN" ]]; then
    DesktopPath=/home/*/桌面
elif [[ "${SYSLANG}" =~ "en_US" ]]; then
    DesktopPath=/home/*/Desktop
fi

for each in "${desktopName}"; do
    if ls $DesktopPath | grep -q $each; then
        rm -f $DesktopPath/$each
    fi
done
if kare -l | grep -q "$pkgName"; then
    kare -P "$pkgName"
fi' >$vpPostRmFile
        chmod a+x $vpPostRmFile
    # fi
    sed -i "s/^Package:.*/Package: $pkgName/" $vpControlFile
    sed -i "s/^Version:.*/Version: $pkgVersion/" $vpControlFile
    sed -i "s/^Architecture:.*/Architecture: $archValue/" $vpControlFile
    sed -i "s/^Depends:.*/Depends: kare/" $vpControlFile
    sed -i "s/pkgName=.*/pkgName=$karePkgName/" $vpPostRmFile
    sed -i "s/pkgVersion=.*/pkgVersion=$pkgVersion/" $vpPostRmFile
    sed -i "s/desktopName=.*/desktopName=\"${desktopValue}\"/" $vpPostRmFile
    cd $vpWS && dpkg -b "vp" "${pkgName}_${pkgVersion}_${archValue}.deb"
    if [ $? -eq 0 ]; then
        if ! (fuser /var/lib/dpkg/lock-frontend && fuser /var/lib/dpkg/lock) >/dev/null 2>&1; then
            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
            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
    else
        echo "ERROR - 虚包打包失败" | tee -a $logFile
        return -1
    fi
    [ $? -ne 0 ] && echo "ERROR - VP Config Failed" >>$logFile
    cd - >/dev/null
    for x in $vpWS/vp/*; do
        if [ $x != "$vpWS/vp/DEBIAN" ]; then
            rm -rf $x
        fi
    done
}

function main() {
    while getopts ":e:i:r:P:lhEb:L:S:" 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
            ;;
        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
            ;;
        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"
                ;;
            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"
                ;;
            *)
                echo -e "\e[1mkare: \e[31m错误: \e[0m-e 输入参数错误,可选选项:"
                printf "%-20s%-20s%-20s%-20s\n" "ubuntu16.04" "ubuntu18.04" "ubuntu20.04" "ubuntu22.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
                ;;
            openkylin1.0)
                buildEnv kare-ok1
                ;;
            openkylin2.0)
                buildEnv kare-ok2
            ;;
            v10)
                buildEnv kare-v10
                ;;
            v10sp1)
                buildEnv kare-v10sp1
                ;;
            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"
                printf "%-20s%-20s%-20s\n" "v4" "v10" "v10sp1"
                printf "%-20s%-20s\n" "openkylin1.0" "openkylin2.0"
                printf "%-20s%-20s\n" "local"
                exit -1
                ;;
            esac
            exit 0
            ;;
        h)
            printUsage
            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
    else
        echo "命令无效"
        printUsage
        exit 1
    fi
}

main "$@"
