#!/bin/bash

# tmp='tes+sdf_2.2+sdfks/sd\f_amd64.deb'
# echo $tmp | sed -r 's/(\+|\/|\\)//g'

Exec='/usr/share/code/code\ --no-sandbox\ --unity-launch'
echo $Exec | sed 's|\\ --| --|g'

exit 0

# if [ -n $(ls -d /.fs.old-*) ]; then
#     echo 123
# else
#     echo 234
# fi

# exit 0

eachReault="/home/zhanglin/桌面/test.desktop"
execSegment=$(grep -m 1 '^Exec=' ${eachReault} | sed 's/^Exec=//')
[[ "${execSegment}" =~ "KARE" ]] && echo "已改，退出" && exit 0
echo "execSegment: ${execSegment}"

execOption=$(echo $execSegment | egrep -o "(--.*|%[a-zA-Z])")

execTmp1=$(echo $execSegment | sed -r 's/^(\/usr\/bin\/bash |\/bin\/bash |bash |sh |\/bin\/sh |\/usr\/bin\/sh )//')
execTmp2=${execTmp1% \%[a-zA-Z]}
execCmd=${execTmp2%% *}

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

sed -i "1,/^Exec=/{s|^Exec=|#Exec=|}" $eachReault
sed -i "/#Exec=/a\Exec=${execCmd}KARE ${execOption}" $eachReault

exit 0

#日志级别 debug-1, info-2, warn-3, error-4, always-5
LOG_LEVEL=1

#调试日志
function log_debug() {
    content="[DEBUG] $(date '+%Y-%m-%d %H:%M:%S') $@"
    [ $LOG_LEVEL -le 1 ] && echo -e "\033[32m" ${content} "\033[0m"
}
#信息日志
function log_info() {
    content="[INFO ] $(date '+%Y-%m-%d %H:%M:%S') $@"
    [ $LOG_LEVEL -le 2 ] && echo -e "\033[32m" ${content} "\033[0m"
}
#警告日志
function log_warn() {
    content="[WARN ] $(date '+%Y-%m-%d %H:%M:%S') $@"
    [ $LOG_LEVEL -le 3 ] && echo -e "\033[33m" ${content} "\033[0m"
}
#错误日志
function log_err() {
    content="[ERROR] $(date '+%Y-%m-%d %H:%M:%S') $@"
    [ $LOG_LEVEL -le 4 ] && echo -e "\033[31m" ${content} "\033[0m"
}
#一直都会打印的日志
function log_always() {
    content="[ALWAY] $(date '+%Y-%m-%d %H:%M:%S') $@"
    [ $LOG_LEVEL -le 5 ] && echo -e "\033[32m" ${content} "\033[0m"
}

function INSTALL_FUN() {
    debName=${1}
    # 容器选型
    containerType ${debName} - >containerTypeValue
    if [ ${containerTypeValue} == "docker" ]; then
        # 容器名称
        containerName ${debName} - >containerNameValue
        # 判断容器是否存在
        checkContainerExist ${debName} - >containerExistFlag
        if ${containerExistFlag}; then
            exit 0
        else
            # 软件包解析
            parseDeb ${debName} - softwareVersionNum softwareArch >softwareNameValue
            # 获取安装环境
            getInstallEnv ${debName} - >baseOSEnv
            # 创建容器
            createContainer ${containerNameValue} ${baseOSEnv}
            # 启动容器
            startContainer ${containerNameValue}
            # 安装软件包
            installDebInContainer ${debName} ${containerNameValue}
            # 复制desktop等必要资源至宿主机
            cpResourceToHost ${containerNameValue}
        fi
    elif [ ${containerTypeValue} == "podman" ]; then
        # 暂不涉及
    elif [ ${containerTypeValue} == "other" ]; then
        # 暂不涉及
    fi
    # 虚包管理
    vpManager ${softwareNameValue} ${softwareVersionNum} ${softwareArch}
    # 配置管理
    configManager ${softwareNameValue} ${softwareVersionNum}
}

function createContainer() {
    # 容器名称
    containerNameValue=
    # 容器环境变量
    containerEnv='-e DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus -e QT_X11_NO_MITSHM=1'
    # 容器登录用户
    containerUidUser=1000
    # 容器共享目录
    mntContainerShareDir - >containerSharedDir
    # 创建容器
    ${containerTypeValue} create --privileged -u ${containerUidUser} --name ${containerNameValue} \ 
    ${containerEnv} ${containerSharedDir} ${baseOSEnv}
}

function installDebInContainer() {
    # 复制软件包至容器
    ${containerTypeValue} cp ${debName} ${containerNameValue}:/
    # 安装命令
    sudopassword="qwer1234"
    containerDebInstallCmd="echo ${sudopassword} | sudo -S apt update && sudo apt -f install -y ${debName}"
    # 执行
    ${containerTypeValue} exec ${containerNameValue} /bin/bash -c "${containerDebInstallCmd}"
    pipestatus=("${PIPESTATUS[@]}")
    if [ "${pipestatus[0]}" -ne 0 ]; then
        ${containerTypeValue} rm -f ${containerNameValue} >/dev/null
        exit -1
    fi
}

function vpManager() {
    pkgName="$1""-kare"
    karePkgName="$1"
    pkgVersion="$2"
    archValue="$3"
    [ ! -d $vpWS ] && mkdir -p $vpWS/vp/DEBIAN
    if [ ! -f $vpControlFile -o ! -f $vpPostRmFile ]; then
        echo "WARNING - VP File Not Exists"
        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=

if kare -l | grep "$pkgName" | grep -q "$pkgVersion"; then
    kare -r "$pkgName" "$pkgVersion"
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
    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"
                sleep 1
                ((count--))
                [ $count -le 0 ] && break
            done
            dpkg -i --force-overwrite ${pkgName}_${pkgVersion}_${archValue}.deb
        fi
    else
        echo "ERROR - 虚包打包失败"
        return -1
    fi
    [ $? -ne 0 ] && echo "ERROR - VP Config Failed"
    cd - >/dev/null
    for x in $vpWS/vp/*; do
        if [ $x != "$vpWS/vp/DEBIAN" ]; then
            rm -rf $x
        fi
    done
}

function REMOVE_FUN() {
    local softwareDebName=${1}
    local softwareDebVersionNum=${2}
    # 根据软件名和版本号判断所属容器
    removeContainerExist ${softwareDebName} ${softwareDebVersionNum} - removeContainerName >removeContainerExistFlag
    if not ${removeContainerExistFlag}; then
        exit -1
    else
        # 删除容器
        removeContainer ${removeContainerName}
        # 卸载虚包
        removeVirtualPackage ${softwareDebName}
        # 卸载配置管理
        removeConfigManager ${softwareDebName} ${softwareDebVersionNum}
    fi
}

function upgradeRun() {
    Exec=${1}
    baseOSEnv=${2}
    # 容器选择器
    containerSelector ${Exec} - >upgradeCompatTool
    # 启动方式
    launchWayWatcher ${Exec} - >launchWay
    # 双击启动
    if [ ${launchWay} == "双击" ]; then
        # 获取偏好值
        getPreferValue ${Exec} - >baseOSEnv
    fi
    # 根据兼容选择器执行相应的启动
    if [ ${upgradeCompatTool} == "Bwrap" ]; then
        # 挂载兼容环境目录
        mntBaseOSEnv ${baseOSEnv} - >baseOSDir
        # 挂载宿主机目录
        mntHostEnv - >hostOSDir
        # 判断登录用户
        uidUser=$(id -u)
        # 判断登录用户组
        gidUserGroup=$(id -g)
        # 设置环境变量
        setBwrapEnv - >bwrapEnv
        # 启动
        bwrap --uid ${uidUser} --gid ${gidUserGroup} ${baseOSDir} ${hostOSDir} ${bwrapEnv} ${Exec}
    elif [ ${upgradeCompatTool} == "Docker" ]; then
        # 暂不使用
    elif [ ${upgradeCompatTool} == "Other" ]; then
        # 暂不涉及
    fi
}

function kareRun() {
    debName="$@"
    # 判断相应容器是否存在
    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
        exit -1
    fi
    # 通过配置文件获取执行命令
    getExecByConf ${debName} - >debExec
    # 启动容器并执行命令
    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
            exit -1
        fi
        dbus-send --system --type=method_call --print-reply \
            --dest=com.kylin.dockerAgent /com/kylin/dockerAgent com.kylin.dockerAgent.dockerAgentRun \
            string:"$eachContainer" string:"$debExec"
    done
}

function RUN_FUN() {
    Exec=${1}
    BaseOS=${2}
    # 字段处理
    processExecSegment ${Exec} - >Exec
    # 场景区分
    sceneDiff ${Exec} - >sceneFlag
    if ${sceneFlag}; then
        # 跨版本升级、换机助手场景
        upgradeRun ${Exec} ${BaseOS}
    else
        # 其他场景
        kareRun ${Exec}
    fi
}

function main() {
    # 解析命令行选项
    while getopts ":e:i:r:P:lh:b:" opt; do
        case $opt in
        i)
            # 判断uid
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            # 执行安装逻辑
            INSTALL_FUN "$@"
            exit
            ;;
        r)
            # 判断uid
            if [ $(id -u) -ne 0 ]; then
                echo -e "\e[1mkare: \e[31m错误: \e[0m所请求的操作需要超级用户权限"
                exit -1
            fi
            # 执行卸载逻辑
            REMOVE_FUN "${@:2}"
            exit
            ;;
        run)
            # 执行运行逻辑
            RUN_FUN "${@:2}"
            ;;
        其他选项)
            # 其他逻辑
            ;;
        esac
    done
}

main "$@"

# KARE Env

function main() {
    scene="$@"
    # 不带参数，跨版本升级或换机助手场景
    if [ $# -eq 0 ]; then
        upgradeFun
    # 带参数，其他场景
    else
        nonUpgradeFun
    fi
}

function upgradeFun() {
    resourcePre="fs.old-"
    # 扫描环境目录
    resourceList=$(find / -maxdepth 1 -type d -name "${resourcePre}*")
    # 构建docker环境，暂未使用
    for resourceDir in $resourceList; do
        # 创建工作空间
        # 创建Dockerfile文件
        # 补充环境变量
        # 补充隔离目录
        # 补充其他信息
        # 构建OCI镜像
    done
    # 根据跨版本升级提供的 deb-desktop 文件，进行处理
    desktopFile=
    # 获取软件包和对应desktop信息
    getDebNameAndDesktopInfo ${desktopFile} - desktopInfo >pkgInfo
    # 获取软件包名称、版本和架构信息
    getDebInfo ${pkgInfo} - pkgVersion pkgArch >pkgName
    # 处理Desktop
    ## 获取Exec字段
    getExecSegment ${desktopInfo} - >execSegment
    ## 处理Exec字段
    processExecSegment ${execSegment} - execCmd >execAidDir
    ## 生成二进制文件
    genBinaryFile ${execAidDir} ${execCmd}
    # 虚包管理
    vpManager ${pkgName} ${pkgVersion} ${pkgArch}

    # 迁移系统服务
    ## 比对此时系统服务和初始系统服务
    diffService ${nowSrvList} ${originSrvList} - >srvList
    ## 处理服务
    processSrvList ${srvList}
}

function nonUpgradeFun() {
    resourcePre="kare-"
    # 扫描环境目录
    resourceList=$(find / -maxdepth 1 -type d -name "${resourcePre}*")
    # 确定镜像名称
    defineISOName ${resourceList} - >dockerIsoName
    # 构建镜像
    if [ ${containerTypeValue}=="docker" ]; then
        # 创建工作空间
        mkDockerWS - >docker_ws
        # 创建Dockerfile文件
        echo "FROM scratch" >${docker_ws}/Dockerfile
        # 补充环境变量
        echo -e "ENV  DISPLAY=:0 \\ \n\t LANG=zh_CN.UTF-8 \\ \n\t GTK_IM_MODULE=fcitx \\ \n\t QT4_IM_MODULE=fcitx \\
 \t XMODIFIERS=@im=fcitx \\ \n\t CLUTTER_IM_MODULE=fcitx \\ \n\t QT_IM_MODULE=fcitx" >>${docker_ws}/Dockerfile
        # 补充隔离目录
        baseOSDir=("/bin" "/etc" "/lib" "/lib64" "/lib32" "/opt" "/sbin" "/usr" "/var")
        # 补充其他信息
        echo "USER 1000" >>${docker_ws}/Dockerfile
        echo 'CMD ["/sbin/init"]' >>${docker_ws}/Dockerfile
        # 构建OCI镜像
        docker build -t ${dockerIsoName} ${docker_ws}
    elif [ ${containerTypeValue}=="podman" ]; then
        # 暂不涉及
    elif [ ${containerTypeValue}=="other" ]; then
        # 暂不涉及
    fi
}
