#!/bin/bash
set -u
set -x 
source /opt/kylin-dev-panel/config/build-kylin-dev-panel-env.conf
ENVDIRPRE="${KARE_ENV_PATH}/kylin-dev-panel-"
ENVDIR="${KARE_ENV_PATH}/kylin-dev-panel-u16"
BWRAP_OPTIONS=""
RTE=
CONFIGDIR='/opt/kylin-dev-panel/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
logFile=$logDir/kylin-dev-panel.log
errorLogFile=$logDir/kylin-dev-panel.log
if [ $(id -u) -eq 0 ]; then
    logDir=/opt/kylin-dev-panel/logs
    logFile=$logDir/kylin-dev-panel.log
    errorLogFile=$logDir/kylin-dev-panel.log
fi
if [ ! -d $logDir ]; then
    mkdir -p $logDir
    touch $logFile
    touch $errorLogFile
elif [ ! -f $logFile ]; then
    touch $logFile
    touch $errorLogFile
fi

vpWS="/opt/kylin-dev-panel/vpws"
vpControlFile="/opt/kylin-dev-panel/vpws/vp/DEBIAN/control"
vpPostRmFile="/opt/kylin-dev-panel/vpws/vp/DEBIAN/postrm"

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

CONFLICTIONPATH=/opt/kylin-dev-panel/config/bus/confliction
SESCONFLICTIONPATH=${CONFLICTIONPATH}/sesbuslist/
SYSCONFLICTIONPATH=${CONFLICTIONPATH}/sysbuslist/
SYSCONFCONFLICTIONPATH=${CONFLICTIONPATH}/sysconflist/
KAREHOST=$(cat /etc/os-release | grep PRETTY_NAME)
XEPHYRCONFIGPATH=/opt/kylin-dev-panel/config/Xephyr-config.conf
echo -e "\n\n\n" >>$logFile
echo $(date) >>$logFile

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

function printUsage() {
    echo "用法: kylin-dev-panel [选项] <命令> [参数]"
    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 <参数>         使用kylin-dev-panel运行软件"
    printf "%-21s%-20s%-20s%-20s%-20s\n" "" "参数说明: <软件包名_软件包版本> <软件执行命令>"
    echo ""
    echo "示例:"
    echo "  kylin-dev-panel -e ubuntu16.04 -i softwareName_version_arch.deb"
    echo "  kylin-dev-panel -b ubuntu16.04"
    echo "  kylin-dev-panel -r softwareName version"
    echo "  kylin-dev-panel -P softwareName"
    echo "  kylin-dev-panel -l"
    echo "  kylin-dev-panel -L softwareName"
    echo "  kylin-dev-panel -S filename"
    echo "  kylin-dev-panel -E"
    echo '  kylin-dev-panel run softwareName_version exec 或 kylin-dev-panel 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/kylin-dev-panel/config/build-kylin-dev-panel-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/kylin-dev-panel/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 /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$DIR
    done
    for DIR in "${OK2KAREDIRS[@]}"; do
        umount -fl /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$DIR
    done
    for DIR in "${OK2KAREDIRS[@]}"; do
        rm -rf /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$DIR /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$DIR /opt/kylin-dev-panel/kylindevpanelshadow/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/"
    # 容器名称
    # 容器环境变量
    if [ "$containerImage" = "baseimage_ok2" -o "$containerImage" = "kylindevpanelbaseimage_shadow" ]; 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"
    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"
    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/kylin-dev-panel/config/bus/:$each/kylin-dev-panel/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" -o "$containerImage" = "kylindevpanelbaseimage_shadow" ]; then
        OK2KAREDIRS=(
            bin
            lib
            lib64
            sbin
            var
            usr
        )
        # 构建overlay
        for DIR in "${OK2KAREDIRS[@]}"; do
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/overlay/upper/$DIR" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/overlay/upper/$DIR"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/overlay/work/$DIR" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/overlay/work/$DIR"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/merged/$DIR" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/merged/$DIR"
            mount -t overlay  overlay -o lowerdir=/$DIR,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/overlay/upper/$DIR,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/overlay/work/$DIR /opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/merged/$DIR
            containerSharedDir=$containerSharedDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$containerNameValue/merged/$DIR:/$DIR"
        done

        containerCreateCmd="$containerTypeValue create --privileged -u 1000 -it --name $containerNameValue $containerEnv $containerSharedDir $containerImage"
    else 
        containerCreateCmd="$containerTypeValue create --privileged -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/kylindevpanelshadow 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 - 无基础环境, 请使用kylin-dev-panel -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" -a "$containerImage" != "kylindevpanelbaseimage_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
                    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" -o "$containerImage" = "kylindevpanelbaseimage_shadow" ];then
                docker cp /opt/kylin-dev-panel/config/container-init $containerNameValue:/usr/bin/
                docker cp /opt/kylin-dev-panel/config/hostAgent $containerNameValue:/usr/bin/
                docker cp /opt/kylin-dev-panel/config/host-spawn $containerNameValue:/usr/bin/
                docker cp /opt/kylin-dev-panel/config/dbus-daemon-proxy $containerNameValue:/usr/bin/
                docker cp /opt/kylin-dev-panel/config/add_namespace_to_conflicted_dbus.sh $containerNameValue:/usr/bin/
                docker cp /opt/kylin-dev-panel/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

			$containerTypeValue exec --user root $containerNameValue /bin/bash /usr/bin/container-init $1 | tee -a $logFile
            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/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 "${SYSCONFPATH}" >>${SYSBUSPATH}/sysconf.same
                else
                ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && echo "${SYSCONFPATH}" >>${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
            $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" -a "$containerImage" != "kylindevpanelbaseimage_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" -a "$containerImage" != "kylindevpanelbaseimage_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 "\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 "${SYSCONFPATH}" >>${SYSBUSPATH}/sysconf.same
            else
            ! grep -q "${EACHCONF}" ${SYSCONFPATH}/sysconf.diff && echo "${SYSCONFPATH}" >>${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

        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" -a "$containerImage" != "kylindevpanelbaseimage_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" -a "$containerImage" != "kylindevpanelbaseimage_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
                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}"

    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

    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/kylin-dev-panel/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/kylin-dev-panel/vpws/vp${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%% *}

        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/kylin-dev-panel/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/kylin-dev-panel/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/kylin-dev-panel/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
                umountOverlay $line
                sed -i "/$localSoftwareNameValue=$localSoftwareVersionNum/d" $INSTALLLIST
                if [ -d "/sysroot" ]; then
                    umountOverlay $line
                    file_list="/opt/kylin-dev-panel/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

            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
            dbus-send --system --type=method_call --print-reply \
                --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerExecMonitor \
                string:"$eachContainer" | tee -a $logFile
        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/kylindevpanelbuild-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
    : >${SESBUSPATH}/sesbus.diff
    : >${SESBUSPATH}/sesbus.same
    : >${SYSBUSPATH}/sysbus.diff
    : >${SYSBUSPATH}/sysbus.same
    : >${SYSCONFPATH}/sysconf.diff
    : >${SYSCONFPATH}/sysconf.same
    [ ! -f "${GSETTINGSPATH}/gsettings.diff" ] && touch ${GSETTINGSPATH}/gsettings.diff
}

function kareManager() {    
    echo $1 $2
    find "/opt/kylin-dev-panel/vpws/vp" -type f | while read -r file; do
        opt_file_path=${file//\/opt\/kylin-dev-panel\/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\/kylin-dev-panel\/vpws\/vp/}"
            echo ${file/\/opt\/kylin-dev-panel\/vpws\/vp/} >> /opt/kylin-dev-panel/vpws/kare_manager_"$1"_"$2"
        elif [[ "$file" == *"/usr/share/dbus-1/system-services/"* ]]; then
            install_service_file_path=${file//\/opt\/kylin-dev-panel\/vpws\/vp/\/opt\/kare}
            cp $file $install_service_file_path
            echo ${file//\/opt\/kylin-dev-panel\/vpws\/vp//} >> /opt/kylin-dev-panel/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/kylin-dev-panel/vpws/kare_manager_"$1"_"$2"
        else
            cp $file ${file//\/opt\/kylin-dev-panel\/vpws\/vp/\/opt\/kare}
            echo ${file//\/opt\/kylin-dev-panel\/vpws\/vp/\/opt\/kare} >> /opt/kylin-dev-panel/vpws/kare_manager_"$1"_"$2"
        fi
    done
    rm -rf /opt/kylin-dev-panel/vpws/vp
    update-desktop-database /opt/kare/usr/share/applications
 }

function vpManager() {
    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
        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
        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 shadowCommit(){
    echo 3 > /proc/sys/vm/drop_caches
}

cryptfsPhraseFile="/opt/kylin-dev-panel/config/work-space/ecryptfs-passphrase"
cryptfsSig="/opt/kylin-dev-panel/config/work-space/ecryptfs-sig"
# kare shadow rm test user
function shadowRm(){
    shadowContainer=$(docker ps -a  | grep -ow $1)
    if [ -z "$shadowContainer" ]; then
        echo ""$shadowContainer" Does not exist on the system, program exits" | tee -a $logFile
        exit -1
    fi
    docker stop $shadowContainer
    docker rm $shadowContainer
    if [ -d "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/" ]; then
        umount -f /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/*
        rm -rf /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1    
    else
        umount -f /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/*
        rm -rf /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1   
    fi
    if [ -d "/kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/"]; then
       umount -f /kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/*
       rm -rf /kylin-dev-panel/kylindevpanelshadow/workspace/$1
    else
       umount -f /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/*
       rm -rf /kylin-dev-panel/kylindevpanelshadow/kare/$1
    fi
    if [ "$#" -eq 2 ];then
        if [ -d "/tmp/runtime-$2" ]; then
            rm -rf "/tmp/runtime-$2"
        fi
        if id "$2" >/dev/null 2>&1; then
            loginctl terminate-user  $2
            userdel $2
            fusermount -uz /run/user/$(id -u $2)/gvfs 2>/dev/null
            fusermount -uz /run/user/$(id -u $2)/doc 2>/dev/null
            fusermount -uz /run/user/$(id -u $2)/portal 2>/dev/null
            rm -rf /run/user/$(id -u $2)
            if [ $? -eq 0 ]; then
                echo "User $2 deleted successfully." >>$logFile
            else
                echo "User $2 deletion failed." >>$logFile
            fi
        else
            echo "User $2 does not exist"  >>$logFile
        fi
    fi
}

#startXephyr name display monitor
#只有需要独立键鼠的时候才指定副屏幕，
#不指定屏幕=指定主屏
function startXephyr(){
 declare -A output_map
    xephyr_output_name=""
    xephyrStartCmd=""
    xephyrParentPID=""
  # 1. 优先使用手动查到的 DISPLAY=:0，若失败再尝试自动检测
      CURRENT_DISPLAY=$(who | grep "(:[0-9])" | awk '{print $5}' | tr -d '()' | head -1)
    export DISPLAY="${CURRENT_DISPLAY:-:0}"
    if ! xrandr --listmonitors &>/dev/null; then
        echo "警告: 无法连接到 $DISPLAY，尝试自动检测可用显示..." >>"$logFile"
        # 自动检测可用的 DISPLAY（兼容 :0、:1、:2 等）
        for d in :1 :0 :2; do
            if xrandr --display "$d" --listmonitors &>/dev/null; then
                export DISPLAY="$d"
                echo "自动切换到 DISPLAY=$d" >>"$logFile"
                break
            fi
        done
        if ! xrandr --listmonitors &>/dev/null; then
            echo "错误: 无法获取显示器信息，请确保 X 服务器已运行。" >>"$logFile"
            exit 1
        fi
    fi

    # 2. 安全获取显示器信息
    input=$(xrandr --listmonitors 2>/dev/null | grep -v "Monitors" | grep -v "Can't open display")
    if [ -z "$input" ]; then
        echo "错误: 未检测到有效的显示器配置。" >>"$logFile"
        exit 1
    fi


# 处理显示器信息
while IFS= read -r entry; do
    device=$(echo "$entry" | awk '{print $4}')
    coordinates=$(echo "$entry" | awk '{print $3}')
    formatted_coordinates=$(echo "$coordinates" | awk -F '+' '{print $2,$3}')

    # 跳过空设备名或坐标
    if [ -z "$device" ] || [ -z "$formatted_coordinates" ]; then
        continue
    fi

    if [[ "$device" == *"VGA"* ]]; then
        vga_pos=$formatted_coordinates
    fi
    output_map["$device"]=$formatted_coordinates
done <<< "$input"

# 检查 output_map 是否为空
if [ ${#output_map[@]} -eq 0 ]; then
    echo "错误: 未解析到有效的显示器设备。" >>"$logFile"
    exit 1
fi

   # declare -A output_map
   # xephyr_output_name=""
   # xephyrStartCmd=""
   # xephyrParentPID=""
   # input=$(xrandr --listmonitors  | grep -v "Monitors")
   # while IFS= read -r entry; do
   #     device=$(echo "$entry" | awk '{print $4}')
   #     coordinates=$(echo "$entry" | awk '{print $3}')
   #     formatted_coordinates=$(echo "$coordinates" | awk -F '+' '{print $2,$3}')
   #     if [[ "$device" == *"VGA"* ]]; then
   #         vga_pos=$formatted_coordinates
   #     fi
   #     output_map["$device"]=$formatted_coordinates
   # done <<< "$input"
    for device in "${!output_map[@]}"; do
        if [ "${output_map[$device]}" != "0 0" ]; then
            xephyr_output_name=$device
        fi
    done

    primaryName=$(xrandr | grep  "connected primary" | awk -F' ' '{print $1}')
    #独立屏幕
    if [ "$addResizeable" = true ]; then  # 检查标志
        # 获取主显示器的物理分辨率
        primary_res=$(xrandr --query | grep " connected primary" | awk '{print $4}' | cut -d '+' -f 1)

        # 获取可用工作区大小（去掉任务栏）
        if command -v xdotool >/dev/null; then
            usable_size=$(xdotool getdisplaygeometry | awk '{print $1 "x" $2}')
        else
        # 回退方案：假设任务栏高度为24px（常见值）
          usable_size=$(echo "$primary_res" | awk -F 'x' '{print $1 "x" ($2-24)}')
        fi

        # 使用可用区域大小启动Xephyr
        xephyrStartCmd="Xephyr :$2 -name kylin-dev-panel -class kylin-dev-panel -title $1 -screen $usable_size -resizeable -br -ac  -noreset"
      #  xephyrStartCmd="Xephyr :"$2" -name kylin-dev-panel -class kylin-dev-panel -title $1 -screen 1200x600 -resizeable"
        $xephyrStartCmd  & >>$logFile 2>&1
    else
        if [ "$#" -eq 3 ] && [ "$3" != "${primaryName}" ];then
            xephyrStartCmd="Xephyr :"$2" -title $1 -br -ac  -noreset -output $3 "
            $xephyrStartCmd  & >>$logFile 2>&1
        else    #非独立屏幕
            xephyrParent $1 & 
            sleep 3
            xephyrParentWid=$(xdotool search --name "$1")
            xephyrStartCmd="Xephyr :"$2" -title $1 -parent $xephyrParentWid -br -ac  -noreset"
            $xephyrStartCmd & >>$logFile 2>&1
            xephyrParentPID=$(ps aux |grep "xephyrParent" | grep "$1" |  grep -v grep | awk '{print $2}')
            if [ -z $xephyrParentPID ]; then
                echo "xephyrParentPID - xephyrParent start failed." >>$logFile
                exit -1
            else
                echo "xephyrParentPID - xephyrParent parent successfully started." >>$logFile
            fi
        fi
    fi
    echo "Xephyr - 启动命令为: $xephyrStartCmd" >>$logFile
    xephyr_pid=$(ps aux | grep Xephyr |grep "title $1" | grep -v grep | awk '{print $2}')
    echo "Xephyr PID: $xephyr_pid" >>$logFile

    if [ -z $xephyr_pid  ]; then
        echo "Xephyr - Xephyr start failed." >>$logFile
        exit -1
    else
        echo "Xephyr - Xephyr successfuly started." >>$logFile
    fi
    if [ ! -f "$XEPHYRCONFIGPATH" ]; then
        touch "$XEPHYRCONFIGPATH"
    fi

    new_workspace="$1=$xephyr_pid"
    IFS='=' read -r key value <<< "$new_workspace"
    key_exists=$(grep -qF -- "$key=" "$XEPHYRCONFIGPATH" && echo "true" || echo "false")
    if [ "$key_exists" = "true" ]; then
        sed -i "s/^$key=.*/$new_workspace/" "$XEPHYRCONFIGPATH"
    else
        if [ -z $xephyrParentPID ]; then
            echo "$new_workspace" >> "$XEPHYRCONFIGPATH"
        else
            echo "$new_workspace,$xephyrParentPID" >> "$XEPHYRCONFIGPATH"
        fi
    fi
}
# kare shadow --run name DISPLAY monitor
function shadowRun(){
    addResizeable=false

    xephyrProcess=$(ps aux | grep Xephyr |grep "title $1" | grep -v grep )
    if [ -n "$xephyrProcess" ];then
        echo "WORKSPACE:$1 already running!" | tee -a $logFile
        exit -1
    fi

    shadowContainer=$(docker ps -a | grep -o $1)
    if [ -z "$shadowContainer" ]; then
        echo ""$1" does not exist on the system, program exits" | tee -a $logFile
        exit -1
    fi
    if [ "$4" = "kylin-dev-panel" ]; then
        for each in /*; do
            if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
               continue
            fi
        
            if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" -o "$each" == "/media" ]; then
                continue
            elif [ $each == "/kylin-dev-panel" ]; then
             continue
            else
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
                mount -t overlay  overlay -o lowerdir=/$each,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            fi
        done
    else
        for each in /*; do
            if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
               continue
            fi
        
            if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
                continue
            elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
             continue
            else
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
                mount -t overlay  overlay -o lowerdir=/$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            fi
    done
    fi

    HOME_DIR=$(getent passwd $(who |awk '{print $1}')| awk -F: '{print $6}') 
    #if [ "$#" -eq 2 ];then
    #    startXephyr $1 $2
    #elif [ "$#" -eq 3 ];then
    #    startXephyr $1 $2 $3
   if [ "$4" = "kylin-dev-panel" ]; then
        addResizeable=true 
        startXephyr $1 $2 $4
   fi

    docker start $1 
    if [ "$4" != "kylin-dev-panel" ]; then
        docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S mount --bind /run/user/1000/$4 /run/user/$(id -u $2)/$4"
        docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown -R $2:$2 /run/user/$(id -u $2)/$4"
    fi
    docker exec -d $1 /bin/bash -c "sed -i -e 's/^Backend=.*/Backend=XRender/' $HOME_DIR/.config/ukui-kwinrc"
    docker exec -d $1 /bin/bash -c "peony-qt-desktop -w -d & "
    docker exec -d $1 /bin/bash -c "ukui-panel & "
    if [ "$4" = "kylin-dev-panel" ]; then
        docker exec -d $1 /bin/bash -c "/usr/bin/ukui-kwin_x11 & "
    fi
    docker exec -d $1 /bin/bash -c "/usr/bin/ukui-menu & "
#     docker cp /opt/kylin-dev-panel/config/ukui-control-center-security-config.json $1:$HOME_DIR/.config/
}

#这个函数用于启动一个配置好的 Docker 容器工作空间，并设置用户环境。
#$1: 工作空间/容器名称    $2: 用户名    $3: 密码    $4: DISPLAY 变量值    $5(可选): 显示器参数
# kare shadow --runWithUser name user pass DISPLAY monitor
function shadowRunWithUser(){
    ##检查 Xephyr 是否已运行
    addResizeable=false

    xephyrProcess=$(ps aux | grep Xephyr |grep "title $1" | grep -v grep )
    if [ -n "$xephyrProcess" ];then
        echo "WOPRKSPACE:$1 already running!" | tee -a $logFile
        exit -1
    fi

    ##检查容器是否存在
    shadowContainer=$(docker ps -a | grep -o $1)
    if [ -z "$shadowContainer" ]; then
        echo ""$1" Does not exist on the system, program exits." | tee -a $logFile
        exit -1
    fi

    ##挂载加密目录
    ecryptfsDir="/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/encryedDir"
    #检查加密目录是否存在
    if [ -d "$ecryptfsDir" ];then
        #调用 configeCryptfsSig 配置加密签名
        configeCryptfsSig
        encryptedDirectoryFile="/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/encryptedDirectory.txt"
        #检查文件是否存在
        if [ ! -f "$encryptedDirectoryFile" ]; then
            echo "Error -- $encryptedDirectoryFile 文件不存在" >>$logFile
            exit -1  
        fi

        #检查文件是否可读
        if [ ! -r "$encryptedDirectoryFile" ]; then
            echo "Error -- 文件不可读" >>$logFile
            exit -1
        fi

        #读取文件内容
        encryptedDirectory=$(cat "$encryptedDirectoryFile")
        echo "$encryptedDirectory" >>$logFile

        # 设置 IFS 为冒号，临时修改分隔符
        IFS=':' read -r -a path_array <<< "$encryptedDirectory"

        # 遍历数组中的每个路径
        for path in "${path_array[@]}"; do
            path="${path#/}"
            echo "当前路径: $path"  >>$logFile
            if [ ! -d "$ecryptfsDir/$path" ];then
                continue
            fi
            #强制卸载可能存在的挂载
            echo "$$ecryptfsDir/$path" >>$logFile
            umount -f "$$ecryptfsDir/$path"
            #提取加密签名
            sig=$(tail -1 "$cryptfsSig" | awk -F'[\\[\\]]' '{print $2}')
            if [ -z "$sig" ]; then
                echo "Error extracting signature" >>$logFile
                #exit -1
            fi
            #使用 eCryptfs 加密文件系统挂载，配置多项加密参数
            #key=passphrase:passphrase_passwd_file=$cryptfsPhraseFile: 从文件读取密码
            #no_sig_cache: 不缓存签名
            #ecryptfs_cipher=aes: 使用 AES 加密算法
            #ecryptfs_key_bytes=32: 32字节密钥长度
            #ecryptfs_enable_filename=y: 启用文件名加密
            #ecryptfs_fnek_sig/ecryptfs_sig: 使用提取的签名
            #ecryptfs_unlink_sigs: 卸载时清除签
            mount -t ecryptfs -o key=passphrase:passphrase_passwd_file="$cryptfsPhraseFile",no_sig_cache,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,ecryptfs_enable_filename=y,ecryptfs_passthrough=n,ecryptfs_enable_filename_crypto=y,ecryptfs_fnek_sig="$sig",ecryptfs_sig="$sig",ecryptfs_unlink_sigs \
            $ecryptfsDir/$path /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/$path 2>&1  | tee -a $logFile
            echo "$?">>$logFile
            echo "$sig">>$logFile
            echo "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/$path/" >>$logFile
            # 检查挂载是否成功
            if mount | grep -q "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/$path"; then
                echo "Successfully mounted encrypted filesystem" >>$logFile
            else
                echo "Failed to mount encrypted filesystem" >>$logFile
                #exit -1
            fi
        done

        # for each in $ecryptfsDir/*; do
        #     if [ ! -d $each ];then
        #         continue
        #     fi
        #     #强制卸载可能存在的挂载
        #     echo "$each" >>$logFile
        #     umount -f "$each"
        #     #提取加密签名
        #     sig=$(tail -1 "$cryptfsSig" | awk -F'[\\[\\]]' '{print $2}')
        #     if [ -z "$sig" ]; then
        #         echo "Error extracting signature" >>$logFile
        #         #exit -1
        #     fi
        #     #使用 eCryptfs 加密文件系统挂载，配置多项加密参数
        #     #key=passphrase:passphrase_passwd_file=$cryptfsPhraseFile: 从文件读取密码
        #     #no_sig_cache: 不缓存签名
        #     #ecryptfs_cipher=aes: 使用 AES 加密算法
        #     #ecryptfs_key_bytes=32: 32字节密钥长度
        #     #ecryptfs_enable_filename=y: 启用文件名加密
        #     #ecryptfs_fnek_sig/ecryptfs_sig: 使用提取的签名
        #     #ecryptfs_unlink_sigs: 卸载时清除签
        #     mount -t ecryptfs -o key=passphrase:passphrase_passwd_file="$cryptfsPhraseFile",no_sig_cache,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,ecryptfs_enable_filename=y,ecryptfs_passthrough=n,ecryptfs_enable_filename_crypto=y,ecryptfs_fnek_sig="$sig",ecryptfs_sig="$sig",ecryptfs_unlink_sigs \
        #     $each /shadow/workspace/$1/merged/$(basename "$each") 2>&1  | tee -a $logFile
        #     echo "$?">>$logFile
        #     echo "$sig">>$logFile
        #     echo "/shadow/workspace/$1/merged/$(basename "$each")/" >>$logFile
        #     # 检查挂载是否成功
        #     if mount | grep -q "/shadow/workspace/$1/merged/$(basename "$each")"; then
        #         echo "Successfully mounted encrypted filesystem" >>$logFile
        #     else
        #         echo "Failed to mount encrypted filesystem" >>$logFile
        #         #exit -1
        #     fi
        # done
    fi

    ##设置 overlay 文件系统
     if [ "$6" = "kylin-dev-panel" ]; then
        for each in /*; do
            if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
               continue
            fi
        
            if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" -o "$each" == "/media" ]; then
                continue
            elif [ $each == "/kylin-dev-panel" ]; then
             continue
            else
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
                mount -t overlay  overlay -o lowerdir=/$each,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            fi
        done
    else
        for each in /*; do
         if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
         fi
         if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
            continue
         elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
            continue
            else
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
                mount -t overlay  overlay -o lowerdir=/$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            fi
        done
    fi

    ##启动 Xephyr 显示服务器
    if [ "$6" = "kylin-dev-panel" ]; then
    addResizeable=true 
    startXephyr $1 $4 $6
    fi

    ##启动容器并配置
    docker start $1 
    #修改 UKUI 窗口管理器的渲染后端为 XRender
    docker exec -d $1 /bin/bash -c "sed -i -e 's/^Backend=.*/Backend=XRender/' /home/$2/.config/ukui-kwinrc"
    if [ "$6" != "kylin-dev-panel" ]; then
        docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S mount --bind /run/user/1000/$6 /run/user/$(id -u $2)/$6"
        docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown -R $2:$2 /run/user/$(id -u $2)/$6"
    fi
    docker exec -u root $1 /bin/bash -c "setfacl -m u:$2:rw /dev/snd/*"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S  chown -R $2:$2 /run/user/$(id -u $2)"
    ##停止并重启系统服务
    systemctl stop kylin-system-updater.service
    killall aptd 
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S /usr/share/kylin-system-updater/kylin-system-updater -r"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S /usr/sbin/aptd -r"
    sleep 3
    # docker cp /opt/kylin-dev-panel/config/ukui-control-center-security-config.json $1:/home/$2/.config/

    ##启动 LightDM 显示管理器
    # 1. 启动 LightDM
    docker exec -d $1 /bin/bash -c "bash /usr/bin/startLightdm.sh $1 $2 $3 $4 $5 $6"

# 2. 等待 LightDM 完全启动（15秒 + 主动检测）
    sleep 15
    until docker exec $1 pgrep lightdm >/dev/null; do sleep 1; done

# 5. 启动 PulseAudio（确保独占启动）
    docker exec -d --user $(id -u $2):$(id -u $2) $1 /bin/bash -c "
    export XDG_RUNTIME_DIR=/run/user/$(id -u $2)
    exec /usr/bin/pulseaudio --daemonize=no --log-target=journal"

# 6. 日志记录
    echo "LightDM 和 PulseAudio 已启动 (XDG_RUNTIME_DIR=/run/user/$(id -u $2))" >> $logFile
    echo "Lightdm-session - 启动命令为: docker exec  -d $1 /bin/bash -c "bash /usr/bin/startLightdm.sh $1 $2 $3 $4 $5 $6""  >>$logFile
}
function shaodowSuspend(){
    shadowContainer=$(docker ps -a | grep -o $1)
    if [ -z "$shadowContainer" ]; then
        echo ""$1" Does not exist on the system, program exits." | tee -a $logFile
        exit -1
    fi
    xdotool  windowunmap $(xdotool search -name $1)
}
#此处还需要该 在哪个屏幕上
#kare shadow --suspend name monitor
function shaodowuSuspend(){
    shadowContainer=$(docker ps -a | grep -o $1)
    if [ -z "$shadowContainer" ]; then
        echo ""$1" Does not exist on the system, program exits." | tee -a $logFile
        exit -1
    fi
    xdotool  windowmap $(xdotool search -name $1)
    sleep 0.2
    position=$(xrandr --listmonitors | grep $2 |  awk '{print $3}' |awk -F '+' '{print $2,$3}')
    x=$(echo $position |awk -F ' ' '{ print $1 }')
    y=$(echo $position |awk -F ' ' '{ print $2 }')
    if [ "$#" -eq 1 ];then
        wmctrl -r $1 -e 0,1920,0,-1,-1 
    elif [ "$#" -eq 2 ];then
        wmctrl -r $1 -e 0,$x,$y,-1,-1 
    elif [ "$#" -eq 3 ];then
        wmctrl -r $1 -e 0,$x,$y,-1,-1 
        return      
    fi
    wmctrl -r $1 -b toggle,fullscreen
}

function shadowStop(){
    shadowContainer=$(docker ps -a | grep -o $1)
    if [ -z "$shadowContainer" ]; then
        echo ""$1" Does not exist on the system, program exits." | tee -a $logFile
        exit -1
    fi
    docker stop $shadowContainer
    workspace_exists=$(grep -qF -- "$1=" "$XEPHYRCONFIGPATH" && echo "true" || echo "false")
    if [ "$workspace_exists" = "true" ]; then
        workspacePid=$(awk -F '=' '/^'$1'=/ {print $2}' "$XEPHYRCONFIGPATH")
        IFS=',' read -r XephyrPID parenetPID <<< "$workspacePid"
        for pid in "$XephyrPID" "$parenetPID"; do
        if kill "$pid" 2>/dev/null; then
            echo "Successfully killed process $pid" >>$logFile
        else
            echo "Failed to kill process $pid (maybe it doesn't exist)" >>$logFile
        fi
        done
        sed -i '/^'$1'=/d' "$XEPHYRCONFIGPATH" >>$logFile
    else
        echo ""$shadowContainer" workspcae doex not exist,program exits." | tee -a $logFile
        # exit -1
    fi

    #卸载掉加密的数据
    ecryptfsDir="/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/encryedDir"
    # if [ -d "$ecryptfsDir" ];then
    #     for each in $ecryptfsDir/*; do
    #         if [ ! -d $each ];then
    #             continue
    #         fi
    #         umount -f "/shadow/workspace/$1/merged/$(basename "$each")"
    #     done
    # fi
    if [ -d "$ecryptfsDir" ];then
        encryptedDirectoryFile="/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/encryptedDirectory.txt"
        #检查文件是否存在
        if [ ! -f "$encryptedDirectoryFile" ]; then
            echo "Error -- $encryptedDirectoryFile 文件不存在" >>$logFile
            # exit -1
        else
            #检查文件是否可读
            if [ ! -r "$encryptedDirectoryFile" ]; then
                echo "Error -- 文件不可读" >>$logFile
                # exit -1
            else
                #读取文件内容
                encryptedDirectory=$(cat "$encryptedDirectoryFile")
                echo "$encryptedDirectory" >>$logFile

                # 设置 IFS 为冒号，临时修改分隔符
                IFS=':' read -r -a path_array <<< "$encryptedDirectory"

                # 遍历数组中的每个路径
                for path in "${path_array[@]}"; do
                    path="${path#/}"
                    echo "当前路径: $path"  >>$logFile
                    if [ ! -d "$ecryptfsDir/$path" ];then
                        continue
                    fi
                    umount -f "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$1/merged/$path"
                done
            fi
        fi
    fi

    systemctl start kylin-system-updater.service
    killall aptd 
    exit 0
}
# kare shadow --new name DISPLAY monitor(最后一个参数可不传)
function shadowNew(){
    addResizeable=false
    wsContainer=$(docker ps -a | grep shadow | grep -o $1)
    if [ -n "$wsContainer" ]; then
        echo "工作空间:"$wsContainer" already exists on the system, please do not create it again." | tee -a $logFile
        exit -1
    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/"
    if [ "$4" = "kylin-dev-panel" ]; 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 XDG_CURRENT_DESKTOP=UKUI \
            -e DISPLAY=:$2 \
            -e SESSION_START=xephyr \
            -e XDG_SESSION_TYPE=x11 \
            -e WORKSPACE_NAME=$1 \
            -e browser_agent_env=true"
    else
        containerEnv="-e WAYLAND_DISPLAY=$4 \
            -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 XDG_CURRENT_DESKTOP=UKUI \
            -e DISPLAY=:$2 \
            -e SESSION_START=xephyr \
            -e XDG_SESSION_TYPE=wayland \
            -e WORKSPACE_NAME=$1 \
            -e browser_agent_env=true"
    fi
if [ "$4" = "kylin-dev-panel" ]; then
    if [[ -n "$3" && "$3" == *","* ]]; then
      shadowDir=
         IFS=',' read -ra dirPairs <<< "$3"
        
        # 首先收集根目录下存在的目录
        existingRootDirs=()
        for each in /*; do
            [ -d "$each" ] && existingRootDirs+=("$each")
        done
        
        # 处理特殊目录（保持原逻辑不变）
        for each in "${existingRootDirs[@]}"; do
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
                shadowDir="$shadowDir -v $each:$each"
            elif [ $each == "/kylin-dev-panel" ]; then
                continue
            fi
        done   
        # 处理第五个参数中的挂载点
        for pair in "${dirPairs[@]}"; do
            cleanPair=$(echo "$pair" | xargs)
            srcPath=$(echo "$cleanPair" | awk -F':' '{print $1}')
            
            # 检查是否在根目录中存在
            inRootDir=false
            for each in "${existingRootDirs[@]}"; do
                if [ "$srcPath" = "$each" ]; then
                    inRootDir=true
                    break
                fi
            done   
            # 如果是特殊目录，已经处理过，跳过
            if [ "$srcPath" == "/dev" -o "$srcPath" == "/sys" -o "$srcPath" == "/tmp" -o "$srcPath" == "/backup" -o "$srcPath" == "/proc" -o "$srcPath" == "/run" -o "$srcPath" == "/media" ]; then
                continue
            elif [ "$srcPath" == "/kylin-dev-panel" ]; then
                continue
            # 如果在根目录中，使用overlay处理
            elif [ "$inRootDir" = true ]; then
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath"
                mount -t overlay overlay -o lowerdir=$srcPath,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath
                shadowDir=$shadowDir" -v /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath:$srcPath"
            # 不在根目录中，直接挂载
            else
                shadowDir="$shadowDir -v $cleanPair"
            fi
        done
        
        # 处理根目录中不在第3个参数列表中的目录（使用overlay）
            for each in "${existingRootDirs[@]}"; do
            # 跳过特殊目录（已经处理过）
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" -o $each == "/media" ]; then
                continue
            elif [ $each == "/kylin-dev-panel" ]; then
                continue
            fi
            
            # 检查是否在第3个参数列表中
            inList=false
            for pair in "${dirPairs[@]}"; do
                srcPath=$(echo "$pair" | awk -F':' '{print $1}' | xargs)
                if [ "$srcPath" = "$each" ]; then
                    inList=true
                    break
                fi
            done
            
            # 如果不在列表中，使用overlay处理
            if [ "$inList" = false ]; then
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each"
                mount -t overlay overlay -o lowerdir=$each,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each
                shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
            fi
            done
    else
        shadowDir=
        for each in /*; do
            if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
            fi
         if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" -o $each == "/media" ]; then
            shadowDir="$shadowDir -v $each:$each"
            elif [ $each == "/kylin-dev-panel" ]; then
            continue
         else
            [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
            [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
            [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
            mount -t overlay  overlay -o lowerdir=/$each,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            shadowDir=$shadowDir" -v /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
         fi
        done
    fi
        shadowDir="$shadowDir -v /kylin-dev-panel:/kylin-dev-panel"
else
    if [[ -n "$3" && "$3" == *","* ]]; then
      shadowDir=
         IFS=',' read -ra dirPairs <<< "$3"
        
        # 首先收集根目录下存在的目录
        existingRootDirs=()
        for each in /*; do
            [ -d "$each" ] && existingRootDirs+=("$each")
        done
        
        # 处理特殊目录（保持原逻辑不变）
        for each in "${existingRootDirs[@]}"; do
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
                shadowDir="$shadowDir -v $each:$each"
            elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
                continue
            fi
        done   
        # 处理第五个参数中的挂载点
        for pair in "${dirPairs[@]}"; do
            cleanPair=$(echo "$pair" | xargs)
            srcPath=$(echo "$cleanPair" | awk -F':' '{print $1}')
            
            # 检查是否在根目录中存在
            inRootDir=false
            for each in "${existingRootDirs[@]}"; do
                if [ "$srcPath" = "$each" ]; then
                    inRootDir=true
                    break
                fi
            done   
            # 如果是特殊目录，已经处理过，跳过
            if [ "$srcPath" == "/dev" -o "$srcPath" == "/sys" -o "$srcPath" == "/tmp" -o "$srcPath" == "/backup" -o "$srcPath" == "/proc" -o "$srcPath" == "/run" ]; then
                continue
            elif [ "$srcPath" == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
                continue
            # 如果在根目录中，使用overlay处理
            elif [ "$inRootDir" = true ]; then
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath"
                mount -t overlay overlay -o lowerdir=$srcPath,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath
                shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath:$srcPath"
            # 不在根目录中，直接挂载
            else
                shadowDir="$shadowDir -v $cleanPair"
            fi
        done
        
        # 处理根目录中不在第3个参数列表中的目录（使用overlay）
            for each in "${existingRootDirs[@]}"; do
            # 跳过特殊目录（已经处理过）
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
                continue
            elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
                continue
            fi
            
            # 检查是否在第3个参数列表中
            inList=false
            for pair in "${dirPairs[@]}"; do
                srcPath=$(echo "$pair" | awk -F':' '{print $1}' | xargs)
                if [ "$srcPath" = "$each" ]; then
                    inList=true
                    break
                fi
            done
            
            # 如果不在列表中，使用overlay处理
            if [ "$inList" = false ]; then
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each"
                mount -t overlay overlay -o lowerdir=$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each
                shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
            fi
            done
    else
        shadowDir=
        for each in /*; do
        if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
        fi
        if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
            shadowDir="$shadowDir -v $each:$each"
        elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
            continue
        else
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
            mount -t overlay  overlay -o lowerdir=/$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
        fi
        done
    fi
        shadowDir="$shadowDir -v /opt/kylindevpanelshadow/:/opt/kylindevpanelshadow/"
fi
    containerCreateCmd="docker create --privileged  -it --ipc host --pid host  --name $1 $containerEnv $shadowDir baseimage_kylindevpanelshadow"

    echo "DEBUG - 容器创建命令: $containerCreateCmd" >>$logFile
    $containerCreateCmd >>$logFile 2>&1
    if [ $? -eq 0 ]; then
        echo "DEBUG - docker: ${containerNameValue}create successfully." >>$logFile
    else
        echo "ERROR - 容器${containerNameValue}create faild." >>$logFile
        return -1
    fi
    HOME_DIR=$(getent passwd $(who |awk '{print $1}')| awk -F: '{print $6}') 

    if [ "$4" = "kylin-dev-panel" ]; then
        addResizeable=true 
        startXephyr $1 $2 $4
    fi
    docker start $1 
    # 修改容器中的用户密码
    usernames=$(getent passwd |grep -E "/bin/(bash|sh)$" | grep -vE "nologin|false|sync|shutdown|root" | cut -d: -f1)
    for user in $usernames; do
        docker exec  -d -u root $1 /bin/bash -c "echo $user:qwer1234 | sudo chpasswd"
    done
    docker exec -d $1 /bin/bash -c "sed -i -e 's/^Backend=.*/Backend=XRender/' $HOME_DIR/.config/ukui-kwinrc"
    docker exec -d $1 /bin/bash -c "peony-qt-desktop -w -d & "
    docker exec -d $1 /bin/bash -c "ukui-panel & "
    if [ "$4" = "kylin-dev-panel" ]; then
     docker exec -d $1 /bin/bash -c "/usr/bin/ukui-kwin_x11 & "
    fi
    docker exec -d $1 /bin/bash -c "/usr/bin/ukui-menu & "
    # docker cp /opt/kylin-dev-panel/config/ukui-control-center-security-config.json $1:$HOME_DIR/.config/

}
# kare shadow --newWithUser name user pass DISPLAY (minotor)  
function shadowNewWithNewUser(){
    addResizeable=false
    wsContainer=$(docker ps -a | grep shadow | grep -o $1)
    if [ -n "$wsContainer" ]; then
        echo "WORKSPACE:"$wsContainer" already exists on the system, please do not create it again" | tee -a $logFile
        exit -1
    fi

    if id "$2" &>/dev/null; then
        echo "DEBUG - User $2 already exists"  | tee -a $logFile
    fi
    useradd "$2"

    # 检查用户是否创建成功
    if [ $? -eq 0 ]; then
        echo "DEBUG - User: $2 create successfully." >> $logFile
    else
        echo "DEBUG - User:$2 creat error." >> $logFile
        exit -1
    fi
    echo "$2:$3" | chpasswd
    echo "DEBUG - 用户 $2 的密码已设置。" | tee -a $logFile
    usermod -s /usr/sbin/nologin $2
    userId=$(id -u  $2)
    virtualHostDir="/hostenv"
    PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"
    if [ "$6" = "kylin-dev-panel" ]; then
       XDG_CONFIG_DIRS=/etc/xdg/xdg-ukui:/etc/xdg:${virtualHostDir}/etc/xdg/xdg-ukui:${virtualHostDir}/etc/xdg
    else 
      XDG_CONFIG_DIRS=/etc/xdg/xdg-kylin-wlcom:/etc/xdg
    fi
    XDG_DATA_DIRS="/usr/share/ukui:/usr/local/share/:/usr/share/:\
${virtualHostDir}/usr/share/ukui:${virtualHostDir}/usr/local/share/:${virtualHostDir}/usr/share/"
if [ "$6" = "kylin-dev-panel" ]; 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 XDG_CURRENT_DESKTOP=UKUI \
-e DISPLAY=:$4 \
-e SESSION_START=xephyr \
-e XDG_SESSION_TYPE=x11 \
-e WORKSPACE_NAME=$1 \
-e browser_agent_env=true"
else 
containerEnv="-e WAYLAND_DISPLAY=/run/user/$userId/$6 \
-e QT_X11_NO_MITSHM=1 \
-e XDG_RUNTIME_DIR=/run/user/$(id -u $2)  
-e XDG_DATA_DIRS=${XDG_DATA_DIRS} \
-e XDG_CONFIG_DIRS=${XDG_CONFIG_DIRS} \
-e XDG_CURRENT_DESKTOP=UKUI \
-e DISPLAY=:$4 \
-e SESSION_START=xephyr \
-e XDG_SESSION_TYPE=wayland \
-e WORKSPACE_NAME=$1 \
-e browser_agent_env=true"
fi
if [ "$6" = "kylin-dev-panel" ]; then
  if [[ -n "$5" && "$5" == *","* ]]; then
      shadowDir=
         IFS=',' read -ra dirPairs <<< "$5"
        
        # 首先收集根目录下存在的目录
        existingRootDirs=()
        for each in /*; do
            [ -d "$each" ] && existingRootDirs+=("$each")
        done
        
        # 处理特殊目录（保持原逻辑不变）
        for each in "${existingRootDirs[@]}"; do
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" -o $each == "/media" ]; then
                if [ $each == "/media" ];then
				    shadowDir="$shadowDir -v $each:$each:shared"
		        else           
				    shadowDir="$shadowDir -v $each:$each"
		        fi
            elif [ $each == "/kylin-dev-panel" ]; then
                continue
            fi
        done
        
        # 处理第五个参数中的挂载点
        for pair in "${dirPairs[@]}"; do
            cleanPair=$(echo "$pair" | xargs)
            srcPath=$(echo "$cleanPair" | awk -F':' '{print $1}')
            
            # 检查是否在根目录中存在
            inRootDir=false
            for each in "${existingRootDirs[@]}"; do
                if [ "$srcPath" = "$each" ]; then
                    inRootDir=true
                    break
                fi
            done
            
            # 如果是特殊目录，已经处理过，跳过
            if [ "$srcPath" == "/dev" -o "$srcPath" == "/sys" -o "$srcPath" == "/tmp" -o "$srcPath" == "/backup" -o "$srcPath" == "/proc" -o "$srcPath" == "/run" -o "$srcPath" == "/media" ]; then
                continue
            elif [ "$srcPath" == "/kylin-dev-panel" ]; then
                continue
            # 如果在根目录中，使用overlay处理
            elif [ "$inRootDir" = true ]; then
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath"
                mount -t overlay overlay -o lowerdir=$srcPath,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath
                shadowDir=$shadowDir" -v /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath:$srcPath"
            # 不在根目录中，直接挂载
            else
                shadowDir="$shadowDir -v $cleanPair"
            fi
        done
        
        # 处理根目录中不在第五个参数列表中的目录（使用overlay）
        for each in "${existingRootDirs[@]}"; do
            # 跳过特殊目录（已经处理过）
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" -o $each == "/media" ]; then
                continue
            elif [ $each == "/kylin-dev-panel" ]; then
                continue
            fi
            
            # 检查是否在第五个参数列表中
            inList=false
            for pair in "${dirPairs[@]}"; do
                srcPath=$(echo "$pair" | awk -F':' '{print $1}' | xargs)
                if [ "$srcPath" = "$each" ]; then
                    inList=true
                    break
                fi
            done
            
            # 如果不在列表中，使用overlay处理
            if [ "$inList" = false ]; then
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each"
                [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each"
                mount -t overlay overlay -o lowerdir=$each,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each
                shadowDir=$shadowDir" -v /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
            fi
        done
  else
    shadowDir=
    for each in /*; do
        if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
        fi
        if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" -o "$each" == "/media" ]; then
            shadowDir="$shadowDir -v $each:$each"
        elif [ $each == "/kylin-dev-panel" ]; then
            continue
        else
            [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
            [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
            [ ! -d "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
            mount -t overlay  overlay -o lowerdir=/$each,upperdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            shadowDir=$shadowDir" -v /kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
        fi
    done
    fi
    shadowDir="$shadowDir -v /kylin-dev-panel:/kylin-dev-panel"
else

  if [[ -n "$5" && "$5" == *","* ]]; then
      shadowDir=
         IFS=',' read -ra dirPairs <<< "$5"
        
        # 首先收集根目录下存在的目录
        existingRootDirs=()
        for each in /*; do
            [ -d "$each" ] && existingRootDirs+=("$each")
        done
        
        # 处理特殊目录（保持原逻辑不变）
        for each in "${existingRootDirs[@]}"; do
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
                shadowDir="$shadowDir -v $each:$each"
            elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
                continue
            fi
        done
        
        # 处理第五个参数中的挂载点
        for pair in "${dirPairs[@]}"; do
            cleanPair=$(echo "$pair" | xargs)
            srcPath=$(echo "$cleanPair" | awk -F':' '{print $1}')
            
            # 检查是否在根目录中存在
            inRootDir=false
            for each in "${existingRootDirs[@]}"; do
                if [ "$srcPath" = "$each" ]; then
                    inRootDir=true
                    break
                fi
            done
            
            # 如果是特殊目录，已经处理过，跳过
            if [ "$srcPath" == "/dev" -o "$srcPath" == "/sys" -o "$srcPath" == "/tmp" -o "$srcPath" == "/backup" -o "$srcPath" == "/proc" -o "$srcPath" == "/run" ]; then
                continue
            elif [ "$srcPath" == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
                continue
            # 如果在根目录中，使用overlay处理
            elif [ "$inRootDir" = true ]; then
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath"
                mount -t overlay overlay -o lowerdir=$srcPath,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$srcPath,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$srcPath /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath
                shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$srcPath:$srcPath"
            # 不在根目录中，直接挂载
            else
                shadowDir="$shadowDir -v $cleanPair"
            fi
        done
        
        # 处理根目录中不在第五个参数列表中的目录（使用overlay）
        for each in "${existingRootDirs[@]}"; do
            # 跳过特殊目录（已经处理过）
            if [ $each == "/dev" -o $each == "/sys" -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
                continue
            elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
                continue
            fi
            
            # 检查是否在第五个参数列表中
            inList=false
            for pair in "${dirPairs[@]}"; do
                srcPath=$(echo "$pair" | awk -F':' '{print $1}' | xargs)
                if [ "$srcPath" = "$each" ]; then
                    inList=true
                    break
                fi
            done
            
            # 如果不在列表中，使用overlay处理
            if [ "$inList" = false ]; then
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each"
                [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each"
                mount -t overlay overlay -o lowerdir=$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work$each /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each
                shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
            fi
        done
  else
    shadowDir=
    for each in /*; do
        if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
        fi
        if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
            shadowDir="$shadowDir -v $each:$each"
        elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
            continue
        else
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each"
            mount -t overlay  overlay -o lowerdir=/$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/upper/$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/overlay/work/$each /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each
            shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged$each:$each"
         fi
        done
     fi
        shadowDir="$shadowDir -v /opt/kylindevpanelshadow/:/opt/kylindevpanelshadow/"
  fi
  
    if [ "$6" != "kylin-dev-panel" ]; then
      shadowDir="--device /dev/dri --device /dev/tty0"
 	  shadowDir="$shadowDir -v /run/user/1000/$6:/run/user/$(id -u $2)/$6 "
    fi
    HOST_UID=$(id -u)
    echo $HOST_UID
    HOST_GID=$(id -u)
    echo $HOST_UID
    containerCreateCmd="docker create --privileged  -it --ipc host --pid host  --name $1   $containerEnv $shadowDir  baseimage_kylindevpanelshadow"

    echo "DEBUG - 容器创建命令: $containerCreateCmd" >>$logFile
    $containerCreateCmd >>$logFile 2>&1
    if [ $? -eq 0 ]; then
        echo "DEBUG - 容器${containerNameValue}创建成功" >>$logFile
    else
        echo "ERROR - 容器${containerNameValue}创建失败" >>$logFile
        return -1
    fi
    if [ "$6" = "kylin-dev-panel" ]; then
        addResizeable=true
        startXephyr $1 $4 $6
    fi
    docker start $1 
    # 修改容器中的用户密码
    usernames=$(getent passwd |grep -E "/bin/(bash|sh)$" | grep -vE "nologin|false|sync|shutdown|root" | cut -d: -f1)
    for user in $usernames; do
        docker exec  -d -u root $1 /bin/bash -c "echo $user:qwer1234 | sudo chpasswd"
    done

    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S usermod -s /bin/bash $2"
    docker exec -d $1 /bin/bash -c "sed -i -e 's/^Backend=.*/Backend=XRender/' /home/$2/.config/ukui-kwinrc"
 if [ "$6" != "kylin-dev-panel" ]; then
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S  mkdir -p /run/user/$(id -u $2)"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S  chown -R $2:$2 /run/user/$(id -u $2)"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S  mkdir -p ${XDG_RUNTIME_DIR}/dbus-1"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | dbus-daemon --session --address=unix:path=${XDG_RUNTIME_DIR}/bus --fork --print-address"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown -R $2:$2 /run/user/$userId/$6"
fi
    docker exec -u root $1 /bin/bash -c "groupadd -f audio && usermod -aG audio $2"
    docker exec -u root $1 /bin/bash -c "groupadd -f pulse && usermod -aG pulse $2"
    docker exec -u root $1 /bin/bash -c "setfacl -m u:$2:rw /dev/snd/*"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S  mkdir -p /run/user/$(id -u $2)"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S  chown -R $2:$2 /run/user/$(id -u $2)"    
   # docker exec -d --user $HOST_UID:$HOST_GID $1  /bin/bash -c " /usr/bin/pulseaudio --daemonize=no --log-target=journal &"
    docker cp -a /opt/kylin-dev-panel/config/startLightdm.sh $1:/usr/bin/
    #适配容器内软件的安装和卸载
    systemctl stop kylin-system-updater.service
    killall aptd 
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S /usr/share/kylin-system-updater/kylin-system-updater -r"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S /usr/sbin/aptd -r"

    #sudo 
    # SUDOERS_FILE="/opt/kylin-dev-panel/config/work-space/99-$2-sudo"
    # SUDOERS_LINE="$2 ALL=(ALL:ALL) ALL"
    # echo "$SUDOERS_LINE" > $SUDOERS_FILE
    # docker cp -a $SUDOERS_FILE $1:/etc/sudoers.d/
    # rm -f $SUDOERS_FILE
    # docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown root:root /etc/sudoers.d/99-$2-sudo"
 if [ "$6" != "kylin-dev-panel" ]; then
    # 设置D-Bus环境变量
    docker exec -d $1 /bin/bash -c "export DBUS_SESSION_BUS_ADDRESS=unix:path=${XDG_RUNTIME_DIR}/bus"

    # 创建用户配置文件目录并设置权限

    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S mkdir -p /home/$2/"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown -R $2:$2 /home/$2"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S mkdir -p /home/$2/.log"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown -R $2:$2 /home/$2/.log"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S mkdir -p /home/$2/.config/kylin-wlcom"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown -R $2:$2 /home/$2/.config"


    # 添加渲染组权限
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S groupadd -g \"stat -c '%g' /dev/dri/renderD128\" render"
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S usermod -aG render $2"
    docker exec -d $1 /bin/bash -c "newgrp render"
fi
    # 设置XDG运行时目录
    docker exec -d $1 /bin/bash -c "bash /usr/bin/startLightdm.sh $1 $2 $3 $4 $5 $6" 
    sleep 15
    docker exec  -d --user $(id -u $2):$(id -u $2) $1 /bin/bash -c "
    export XDG_RUNTIME_DIR=/run/user/$(id -u $2)
    exec /usr/bin/pulseaudio --daemonize=no --log-target=journal"
    echo "Lightdm-session - 启动命令为: docker exec  -d $1 /bin/bash -c "bash /usr/bin/startLightdm.sh $1 $2 $3 $4 $5 $6""  >>$logFile

    SUDOERS_FILE="/opt/kylindevpanelshadow/config/work-space/99-$2-sudo"
    SUDOERS_LINE="$2 ALL=(ALL:ALL) ALL"
    echo "$SUDOERS_LINE" > $SUDOERS_FILE
    docker cp -a $SUDOERS_FILE $1:/etc/sudoers.d/
    rm -f $SUDOERS_FILE
    docker exec -d $1 /bin/bash -c "echo qwer1234 | sudo -S chown root:root /etc/sudoers.d/99-$2-sudo"
    exit 0
}

wsConfigPath="/opt/kylindevpanelshadow/config/work-space/template/"
if [ ! -d "$wsConfigPath" ]; then
    mkdir -p "$wsConfigPath"
    echo "创建工作空间配置目录：$wsConfigPath" | tee -a $logFile
fi

#这个函数用于创建一个容器模板，主要功能包括：读取配置文件、创建用户、设置容器环境、创建容器并导出为镜像。
# kare shadow --createTemplate  /path/temp.conf
function shadowCreateTemplate(){
    ##参数获取部分,包括：模板名称、用户名、密码、资源限制(CPU/内存/磁盘)、网络设置、外设配置等
    tempName=$(configtool_kare "get" $1 "clientTemp" "name")
    userName=$(configtool_kare "get" $1 "clientTemp" "username")
    password=$(configtool_kare "get" $1 "clientTemp" "password")
    root=$(configtool_kare "get" $1 "clientTemp" "root")
    cpus=$(configtool_kare "get" $1 "clientTemp" "cpu")
    memory=$(configtool_kare "get" $1 "clientTemp" "memory")
    diskSize=$(configtool_kare "get" $1 "clientTemp" "disk_size")
    deviceWriteBps=$(configtool_kare "get" $1 "clientTemp" "device_write_bps")
    deviceReadBps=$(configtool_kare "get" $1 "clientTemp" "device_read_bps")
    netIsolation=$(configtool_kare "get" $1 "clientTemp" "net_isolation")
    netHostname=$(configtool_kare "get" $1 "clientTemp" "net_hostname")
    netPorts=$(configtool_kare "get" $1 "clientTemp" "net_ports")
    peripheralsUsb=$(configtool_kare "get" $1 "clientTemp" "peripherals_usb")
    peripheralsGpu=$(configtool_kare "get" $1 "clientTemp" "peripherals_gpu")
    peripheralsPrinter=$(configtool_kare "get" $1 "clientTemp" "peripherals_printer")
    peripheralsScanner=$(configtool_kare "get" $1 "clientTemp" "peripherals_scanner")
    packAddress=$(configtool_kare "get" $1 "clientTemp" "pack_address")
    packList=$(configtool_kare "get" $1 "clientTemp" "pack_list")
    encryptedDirectory=$(configtool_kare "get" $1 "clientTemp" "encrypted_directory")
    appBlackList=$(configtool_kare "get" $1 "clientTemp" "app_blacklist")
    echo "创建模板参数：" >> $logFile
    echo "name:" $tempName  >> $logFile
    echo "username:" $userName >> $logFile
    echo "password:" $password >> $logFile
    echo "root:" $root >> $logFile
    echo "cpus:" $cpus >> $logFile
    echo "memory:" $memory >> $logFile
    echo "disk_size:" $diskSize >> $logFile 
    echo "device_write_bps:" "$deviceWriteBps" >> $logFile
    echo "device_read_bps:" "$deviceReadBps" >> $logFile
    echo "net_isolation:" $netIsolation >> $logFile
    echo "net_ports:" $netPorts >> $logFile
    echo "peripherals_usb:" $peripheralsUsb >> $logFile
    echo "peripherals_gpu:" $peripheralsGpu >> $logFile
    echo "peripherals_printer:" $peripheralsPrinter >> $logFile
    echo "peripherals_scanner:" $peripheralsScanner >> $logFile
    echo "pack_address:" $packAddress >> $logFile
    echo "pack_list:" $packList >> $logFile
    echo "encrypted_directory:" $encryptedDirectory >> $logFile
    echo "appBlackList:" $appBlackList 

    ##检查模板是否已存在
    wsTemp=$(docker ps -a | grep $tempName | grep -o $tempName)
    if [ -n "$wsTemp" ]; then
        echo "工作空间:"$wsTemp" 模板已经存在,请勿重复创建" | tee -a $logFile
        exit -1
    fi

    ##用户管理部分
    # 检查用户是否已存在
    if id "$userName" &>/dev/null; then
        echo "DEBUG - 用户 $userName 已经存在"  | tee -a $logFile
        exit -2
    fi
    #创建系统用户
    useradd "$userName"
    if [ $? -eq 0 ]; then
        echo "DEBUG - 用户 $userName 已成功创建。" >> $logFile
    else
        echo "DEBUG - 创建用户 $userName 时出错。" >> $logFile
        exit -3
    fi
    #设置用户密码
    echo "$userName:$password" | chpasswd
    echo "DEBUG - 用户 $userName 的密码已设置。" | tee -a $logFile
    #将用户shell设置为nologin
    usermod -s /usr/sbin/nologin $userName

    ##容器环境变量设置,包括路径、XDG相关变量、显示设置等
    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/"
    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 XDG_CURRENT_DESKTOP=UKUI \
-e DISPLAY=:1 \
-e SESSION_START=xephyr \
-e XDG_SESSION_TYPE=x11 \
-e WORKSPACE_NAME=CLIENTTEMP \
-e browser_agent_env=true"


    # 设置 IFS 为冒号，临时修改分隔符
    IFS=':' read -r -a path_array <<< "$encryptedDirectory"

    # 遍历数组中的每个路径
    for path in "${path_array[@]}"; do
        path="${path#/}"
        echo "当前路径: $path"  >>$logFile
        [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/encryedDir/$path" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/encryedDir/$path"
    done

    ##文件系统挂载准备,特殊目录(/dev, /sys等)直接挂载,加密目录单独处理,其他目录使用overlay文件系统挂载
    shadowDir=
    for each in /*; do
        if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
        fi
        if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
            shadowDir="$shadowDir -v $each:$each"
        elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
            continue
        # elif [ $each == "$encryptedDirectory" ]; then
        #     [ ! -d "/shadow/kare/$tempName/encryedDir/$each" ] && mkdir -p "/shadow/kare/$tempName/encryedDir/$each"
        else
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/overlay/upper/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/overlay/upper/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/overlay/work/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/overlay/work/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/merged/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/merged/$each"
            mount -t overlay  overlay -o lowerdir=/$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/overlay/upper/$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/overlay/work/$each /opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/merged/$each >> $logFile
            shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/merged$each:$each"
        fi
    done
    shadowDir="$shadowDir -v /opt/kylindevpanelshadow/:/opt/kylindevpanelshadow/"
    ##容器创建和启动
    containerCreateCmd="docker create --privileged  -it"
    if [ -n $cpus ];then
        containerCreateCmd="$containerCreateCmd --cpus=$cpus"
    fi
    if [ -n $memory ];then
        containerCreateCmd="$containerCreateCmd -m $memory"
    fi
    if [ -n $diskSize ];then
        # 获取当前存储驱动
        storage_driver=$(docker info --format '{{.Driver}}')
        echo "当前存储驱动: $storage_driver" >>$logFile

        # 检查是否支持 --storage-opt size
        supported_drivers=("devicemapper" "zfs" "btrfs")
        can_use_storage_opt=false

        for driver in "${supported_drivers[@]}"; do
            if [[ "$storage_driver" == "$driver" ]]; then
                can_use_storage_opt=true
                break
            fi
        done

        # 输出检测结果
        if [[ "$can_use_storage_opt" == true ]]; then
            echo "SUCCESS: 当前环境支持 --storage-opt size" >>$logFile
            containerCreateCmd="$containerCreateCmd --storage-opt size=$diskSize"
        else
            echo "WARNING: 当前存储驱动 ($storage_driver) 不支持 --storage-opt size" >>$logFile
        fi
    fi
    if [ -n $deviceWriteBps ];then
        containerCreateCmd="$containerCreateCmd --device-write-bps=$deviceWriteBps"
    fi

    if [ -n $deviceReadBps ];then
        containerCreateCmd="$containerCreateCmd --device-read-bps=$deviceReadBps"
    fi
    containerCreateCmd="$containerCreateCmd  --name $tempName $containerEnv $shadowDir kylindevpanelbaseimage_shadow"
    echo "DEBUG - 容器创建命令: $containerCreateCmd" >>$logFile
    $containerCreateCmd >>$logFile 2>&1
    if [ $? -eq 0 ]; then
        echo "DEBUG - 容器${containerNameValue}创建成功" >>$logFile
    else
        echo "ERROR - 容器${containerNameValue}创建失败" >>$logFile
        userdel $userName
        return -4
    fi
    
    docker start $tempName
    ## 修改容器中的用户密码
    usernames=$(getent passwd |grep -E "/bin/(bash|sh)$" | grep -vE "nologin|false|sync|shutdown|root" | cut -d: -f1)
    for user in $usernames; do
        docker exec  -d -u root $tempName /bin/bash -c "echo $user:qwer1234 | sudo chpasswd"
    done

    ##容器内特定配置
    #修改目标用户的shell为bash
    docker exec -d $tempName /bin/bash -c "echo qwer1234 | sudo -S usermod -s /bin/bash $userName"
    if [ -n "$appBlackList" ];then
        appBlackList=$(echo "$appBlackList" | sed 's/:/ /g')
        docker exec -d $tempName /bin/bash -c "echo qwer1234 | sudo -S  chmod -x $appBlackList"
    fi
    #修改UKUI窗口管理器的配置
    docker exec -d $tempName /bin/bash -c "sed -i -e 's/^Backend=.*/Backend=XRender/' /home/$userName/.config/ukui-kwinrc"
    #复制启动脚本到容器内
    docker cp -a /opt/kylin-dev-panel/config/startLightdm.sh $tempName:/usr/bin/
    ##导出和导入镜像
    docker stop $tempName
    #导出容器为tar文件
    docker export $tempName -o "$wsConfigPath/$tempName.tar"
    if [ $? -eq 0 ]; then
        echo "DEBUG - 镜像已导出" >> $logFile
    else
        echo "DEBUG - 镜像导出出错。" >> $logFile
        userdel $userName
        docker rm $tempName
        umount -f /opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/merged/*
        rm -rf /opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName
        exit -5
    fi
    #导入tar文件为新的镜像
    docker import "$wsConfigPath/$tempName.tar" "$(echo $tempName | tr '[:upper:]' '[:lower:]'):v1"
    if [ $? -eq 0 ]; then
        echo "DEBUG - 镜像已导入" >> $logFile
    else
        echo "DEBUG - 镜像导入出错" >> $logFile
        userdel $userName
        docker rm $tempName
        umount -f /opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName/merged/*
        rm -rf /opt/kylin-dev-panel/kylindevpanelshadow/kare/$tempName
        exit -6
    fi
    #复制配置文件到工作空间配置路径
    cp $1 $wsConfigPath
    exit 0
}

# kare shadow --rmTemplate name
function shadowRmTemplate(){
    confFile=$(grep -rw "$1" $wsConfigPath | awk -F: '{print $1}')
    tempName=$(configtool_kare "get" $confFile "clientTemp" "name")
    userName=$(configtool_kare "get" $confFile "clientTemp" "username")

    tempContainer=$(docker ps -a | grep -o $1)
    if [ -z "$tempContainer" ]; then
        echo "DEBUG - 模板容器($tempContainer)在系统上不存在," | tee -a $logFile
    fi
    docker stop $tempContainer
    docker rm $tempContainer

    tempImage=$(docker images | grep  -i $1)
    if [ -z "$tempImage" ]; then
        echo "DEBUG - 模板镜像($tempContainer)在系统上不存在," | tee -a $logFile
    fi
    docker image rm  $(echo $tempImage | awk '{print $3}')

    if [ -e "$wsConfigPath/$1.tar" ]; then
        rm "$wsConfigPath/$1.tar"
        echo "文件 $"$wsConfigPath/$1.tar" 已被成功删除。" >> $logFile
    fi

    umount -f /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/*
    rm -rf /opt/kylin-dev-panel/kylindevpanelshadow/kare/$1

    if [ -d "/tmp/runtime-$userName" ]; then
        rm -rf "/tmp/runtime-$userName"
    fi
    loginctl terminate-user  $userName
    userdel $userName
    if [ $? -eq 0 ]; then
        echo "DEBUG - 模板用户($userName)删除成功." >>$logFile
    else
        echo "DEBUG - 模板用户($userName)删除失败." >>$logFile
    fi
    rm -f $confFile

}

function configeCryptfsSig(){
    #检查并设置 ecryptfs-passphrase 文件（可能存在问题：硬编码密码、文件权限）
    if [ -z "$(head -n 1 "$cryptfsPhraseFile")" ]; then
        echo "passphrase_passwd=qwer1234" > $cryptfsPhraseFile
    fi
    #检查并生成 ecryptfs-sig 签名文件（可能存在问题：文件权限、如果 ecryptfs-add-passphrase 失败脚本仍会继续执行）
    if [ ! -f "$cryptfsSig" ] || [ -z "$(head -n 1 "$cryptfsSig")" ]; then
        echo "qwer1234" | ecryptfs-add-passphrase --fnek - > "$cryptfsSig" 2>&1
        if [ $? -ne 0 ]; then
            echo "Error generating ecryptfs signature" >>$logFile
            exit 1
        fi
    fi

}

#这个函数用于基于已有模板创建新的容器实例，主要功能包括：检查模板、准备环境、创建容器并启动图形界面。
#函数接收4个参数：$1: tempName - 模板名称    $2: name - 新容器名称    $3: display - 显示名称    $4: monitor - 显示器编号
#kare shadow --createByTemplate tempName name display monitor
function shadowCreateByTemplate(){
    ##检查Docker镜像中是否存在指定的模板镜像
    tempImageName=$(docker images | grep  -wi $1)
    if [ -z "$tempImageName" ]; then
        echo "DEBUG - 模板镜像($1)在系统上不存在" | tee -a $logFile
        exit -1
    fi
    ##检查模板的挂载目录是否存在
    if [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/" ]; then
        echo "DEBUG - 模板镜像($1)环境异常，请重新创建模板" | tee -a $logFile

        exit -2
    fi
    ##配置文件读取
    confFile=$(grep -rw "$1" $wsConfigPath | awk -F: '{print $1}')
    userName=$(configtool_kare "get" $confFile "clientTemp" "username")
    userPasswd=$(configtool_kare "get" $confFile "clientTemp" "password")
    encryptedDirectory=$(configtool_kare "get" $confFile "clientTemp" "encrypted_directory")
    cpus=$(configtool_kare "get" $confFile "clientTemp" "cpus")
    memory=$(configtool_kare "get" $confFile "clientTemp" "memory")
    deviceWriteBps=$(configtool_kare "get" $confFile "clientTemp" "device_write_bps")
    deviceReadBps=$(configtool_kare "get" $confFile "clientTemp" "device_read_bps")

    ##容器环境变量设置
    #包括路径、XDG相关变量、显示设置等,特别注意 DISPLAY=:$4 使用传入的monitor参数
   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/"
    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 XDG_CURRENT_DESKTOP=UKUI \
-e DISPLAY=:$4 \
-e SESSION_START=xephyr \
-e XDG_SESSION_TYPE=x11 \
-e WORKSPACE_NAME=$2 \
-e browser_agent_env=true"
    ##文件系统挂载准备
    shadowDir=
    for each in /*; do
        if [ ! -d "$each" ]; then  # || [ -L "$each" ]; then
            continue
        fi
        if [ $each == "/dev" -o $each == "/sys"  -o $each == "/tmp" -o $each == "/backup" -o $each == "/proc" -o $each == "/run" ]; then
            shadowDir="$shadowDir -v $each:$each"
        elif [ $each == "/opt/kylin-dev-panel/kylindevpanelshadow" ]; then
            continue
        # elif [ $each == "$encryptedDirectory" ]; then
        #     # [ ! -d "/shadow/workspace/$2/overlay/upper/$each" ] && mkdir -p "/shadow/workspace/$2/overlay/upper/$each"
        #     [ ! -d "/shadow/workspace/$2/encryedDir/$each" ] && mkdir -p "/shadow/workspace/$2/encryedDir/$each"
        #     [ ! -d "/shadow/workspace/$2/merged/$each" ] && mkdir -p "/shadow/workspace/$2/merged/$each"
        #     configeCryptfsSig
        #     sig=$(tail -1 "$cryptfsSig" | awk -F'[\\[\\]]' '{print $2}')
        #     if [ -z "$sig" ]; then
        #         echo "Error extracting signature" >>$logFile
        #         #exit -1
        #     fi

        #     mount -t ecryptfs -o key=passphrase:passphrase_passwd_file="$cryptfsPhraseFile",no_sig_cache,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,ecryptfs_enable_filename=y,ecryptfs_passthrough=n,ecryptfs_enable_filename_crypto=y,ecryptfs_fnek_sig="$sig",ecryptfs_sig="$sig",ecryptfs_unlink_sigs \
        #     /shadow/workspace/$2/encryedDir/$(basename "$each") /shadow/workspace/$2/merged/$(basename "$each")  2>&1  | tee -a $logFile
        #     shadowDir=$shadowDir" -v /shadow/workspace/$2/merged/$each:$each"

        #     # 检查挂载是否成功
        #     if mount | grep -q "/shadow/workspace/$2/merged/$(basename "$each")"; then
        #         echo "Successfully mounted encrypted filesystem" >>$logFile
        #     else
        #         echo "Failed to mount encrypted filesystem" >>$logFile
        #         #exit -1
        #     fi           

        else
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/overlay/upper/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/overlay/upper/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/overlay/work/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/overlay/work/$each"
            [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$each" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$each"
            mount -t overlay  overlay -o lowerdir=/opt/kylin-dev-panel/kylindevpanelshadow/kare/$1/merged/$each,upperdir=/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/overlay/upper/$each,workdir=/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/overlay/work/$each /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$each
            shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged$each:$each"
        fi
    done

    echo "$encryptedDirectory" > "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/encryptedDirectory.txt"
    # 设置 IFS 为冒号，临时修改分隔符
    IFS=':' read -r -a path_array <<< "$encryptedDirectory"

    # 遍历数组中的每个路径
    for path in "${path_array[@]}"; do
        path="${path#/}"
        echo "当前路径: $path"  >>$logFile
        [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/encryedDir/$path" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/encryedDir/$path"
        [ ! -d "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$path" ] && mkdir -p "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$path"
        configeCryptfsSig
        sig=$(tail -1 "$cryptfsSig" | awk -F'[\\[\\]]' '{print $2}')
        if [ -z "$sig" ]; then
            echo "Error extracting signature" >>$logFile
            #exit -1
        fi

        mount -t ecryptfs -o key=passphrase:passphrase_passwd_file="$cryptfsPhraseFile",no_sig_cache,ecryptfs_cipher=aes,ecryptfs_key_bytes=32,ecryptfs_enable_filename=y,ecryptfs_passthrough=n,ecryptfs_enable_filename_crypto=y,ecryptfs_fnek_sig="$sig",ecryptfs_sig="$sig",ecryptfs_unlink_sigs \
        /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/encryedDir/$path /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$path  2>&1  | tee -a $logFile
        shadowDir=$shadowDir" -v /opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$path:/$path"

        # 检查挂载是否成功
        if mount | grep -q "/opt/kylin-dev-panel/kylindevpanelshadow/workspace/$2/merged/$path"; then
            echo "Successfully mounted encrypted filesystem" >>$logFile
        else
            echo "Failed to mount encrypted filesystem" >>$logFile
            #exit -1
        fi
    done


    ##添加兼容层挂载
    shadowDir="$shadowDir -v /opt/kylindevpanelshadow/:/opt/kylindevpanelshadow/"
    containerRunCmd="docker create --privileged  -it --ipc host --pid host"
    if [ -n $cpus ];then
        containerRunCmd="$containerRunCmd --cpus=$cpus"
    fi
    if [ -n $memory ];then
        containerRunCmd="$containerRunCmd -m $memory"
    fi
    # if [ -n $disk_size ];then


    # fi
    if [ -n $deviceWriteBps ];then
        containerRunCmd="$containerRunCmd --device-write-bps=$deviceWriteBps"
    fi

    if [ -n $deviceReadBps ];then
        containerRunCmd="$containerRunCmd --device-read-bps=$deviceReadBps"
    fi
    containerRunCmd="$containerRunCmd  --name $2 $containerEnv $shadowDir $(echo "$tempImageName" | awk -F' ' '{print $3}') /bin/bash"
    echo "DEBUG - 通过模板创建容器创建命令: $containerRunCmd" >>$logFile
    $containerRunCmd >>$logFile 2>&1
    if [ $? -eq 0 ]; then
        echo "DEBUG - 容器($2)创建成功" >>$logFile
    else
        echo "ERROR - 容器($2)创建失败" >>$logFile
        return -1
    fi
    
    ##容器启动和配置
    #获取当前用户的家目录
    HOME_DIR=$(getent passwd $(who |awk '{print $1}')| awk -F: '{print $6}') 
    #启动Xephyr显示服务器
    startXephyr $2 $3 $4
    #启动容器
    docker start $2
    #在容器内执行startLightdm.sh脚本启动lightdm显示管理器
    docker exec  -d $2 /bin/bash -c "bash /usr/bin/startLightdm.sh $2 $userName $userPasswd $3" 
    echo "Lightdm-session - 启动命令为: docker exec -d $2 /bin/bash -c "bash /usr/bin/startLightdm.sh $2 $userName $userPasswd $3""  >>$logFile

}
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"
                ;;
            kylindevpanelshadow)
                RTE="kylindevpanelshadow"
                ENVDIR=$ENVDIRPRE"kylindevpanelshadow"
                containerImage=$containerImagePre"kylindevpanelshadow"
                ;;
            *)
                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
                ;;
            kylindevpanelshadow)
                buildEnv kylindevpanelshadow
                ;;
            *)
                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" == "kylindevpanelshadow" ]; then
        if [ $(id -u) -ne 0 ]; then
            echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
            exit -1
        fi
        case ${2} in
            --new)
                shadowNew "${@:3}"
                ;;
            --newWithUser)
                shadowNewWithNewUser "${@:3}"
                ;;
            --run)
                shadowRun "${@:3}"
                ;;
            --runWithUser)
                shadowRunWithUser "${@:3}"
                ;;
            --createTemplate)
                shadowCreateTemplate "${@:3}"
                ;;
            --rmTemplate)
                shadowRmTemplate "${@:3}"
                ;;
            --createByTemplate)
                shadowCreateByTemplate "${@:3}"
                ;;
            --stop)
                shadowStop "${@:3}"
                ;;
            --suspend)
                shaodowSuspend "${@:3}"
                ;;
            --unsuspend)
                shaodowuSuspend "${@:3}"
                ;;
            --rm)
                shadowRm "${@:3}"
                ;;
            --commit)
                shadowCommit
                ;;
           *)
                exit -1
                ;;
        esac
    elif [ "$1" == "list" ]; then
        listFun
    else
        echo "命令无效"
        printUsage
        exit 1
    fi
}

main "$@"
