#!/bin/sh

# vim:set ft=sh sw=2 sts=2 et:

# export systemd environment to avoid environment be replaced by dde-session
# fix https://github.com/linuxdeepin/developer-center/issues/6225
# the following environment variables need to be excluded, otherwise it will affect the startup of some applications
EXCLUDED_ENV="XDG_VTNR\|XDG_SESSION_ID\|XDG_SEAT\|XDG_SESSION_TYPE\|XMODIFIERS\|GTK_IM_MODULE\|QT_IM_MODULE\|CLUTTER_IM_MODULE\|SDL_IM_MODULE"

eval "$(
	busctl --json=short --user get-property org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager Environment |
		jq .data\[\] --raw-output |
		grep -v "$EXCLUDED_ENV" | # handle special character in environment
		sed -r 's/\\/\\\\/' |
		sed -r 's/'\''/\\'\''/' |
		sed -r 's/"/\\"/' |
		sed -r 's/\$/\\$/' |
		sed -r 's/^([^=]+)=(.*)$/export \1="\2"/'
)"

get_graphics_drivers() {
    targets="$@"  # 接收所有传入的参数
    directories="/sys/class/drm/card0/device/drm/card0/device/driver/module/drivers /sys/bus/pci/drivers/"  # 要搜索的目录列表
    for target_to_match in $targets; do
        for directory in $directories; do
            # 遍历指定目录
            for file in "$directory"/*; do
		if [ -L "$file" ]; then
                    # 文件为符号链接
                    driver_name=$(basename "$(readlink "$file")")
                else
                    # 文件为普通文件
                    driver_name=$(basename "$file")
                fi
                # 检查是否等于目标驱动程序
                if [ "$driver_name" = "$target_to_match" ]; then
                    echo "Match found: $driver_name"
                    return 0
                fi
            done
        done
    done
    return 1  # 默认返回1表示匹配失败
}

if [ "$1" = "/usr/bin/dde-session" ]; then
    if [ -f "$HOME/.dde_env" ]; then
        . "$HOME/.dde_env"
        # Handling configuration migration issues
        if [ -n "$QT_SCALE_FACTOR" ]; then
            unset QT_SCALE_FACTOR
            unset QT_SCREEN_SCALE_FACTORS
            unset QT_AUTO_SCREEN_SCALE_FACTOR
            unset QT_FONT_DPI
            export STARTDDE_MIGRATE_SCALE_FACTOR=1
        fi
    elif [ -f "$HOME/.pam_environment" -a -n "$QT_SCALE_FACTOR" ]; then
        # Handling configuration migration issues for earlier version
        unset QT_SCALE_FACTOR
        export STARTDDE_MIGRATE_SCALE_FACTOR=1
    fi
    # control qt program infos level, set it only on uos
    if [ -f "/etc/uos-version" ];then
        if ! grep -q Community /etc/uos-version;then
            export QT_LOGGING_RULES="*.debug=false"
        fi
    fi
    # set qt qpa platform type
    export QT_QPA_PLATFORM="dxcb;xcb"
    # control qml softwarecontext in loongson-drm
    get_graphics_drivers "driver=loongson-drm"
    if [ $? -eq 0 ];then
        export QMLSCENE_DEVICE=softwarecontext
    fi
fi
