#!/bin/bash
exec > /dev/null 2>&1

SHOWUI="/usr/bin/showUI_CITIC_R"
function getUser
{
    user=
    userPath=/run/systemd/users
    userFiles=`ls $userPath` 
    for userFile in $userFiles
    do  
        if [ "${userFile}" -ge "500" ];then
            userState=`awk -F= '{ if($1=="STATE") print $2}' ${userPath}/${userFile}`
            if [ ${userState} == "active" ];then
                user=`awk -F= '{ if($1=="NAME") print $2}' ${userPath}/${userFile}`
                ONLINE_SEATS=`awk -F= '{ if($1=="ONLINE_SEATS") print $2}' ${userPath}/${userFile}`
                SESSIONSID=`awk -F= '{ if($1=="DISPLAY") print $2}' ${userPath}/${userFile}`
                break
            fi  
        fi  
    done

    if [ "$user" == "" ];then
        user=root
    fi  
    echo $user
}

get_user_xdisplay() {
    local uid="$1"
    local program_name="${2:-Xwayland}"  # 默认使用Xwayland
    local display=""

    # 获取程序的基本名称（去掉路径）
    local base_name=$(basename "$program_name")

    # 查找指定用户的X服务器进程
    while IFS= read -r line; do
        # 提取进程命令行参数
        local args=$(echo "$line" | awk '{$1=$2=$3=""; print $0}')

        # 从参数中提取显示编号
        for arg in $args; do
            if [[ "$arg" =~ ^:[0-9]+$ ]]; then
                display="$arg"
                break 2  # 找到后跳出两层循环
            fi  
        done
    done < <(ps -u "$uid" -o pid,user,args | grep -E "[${base_name:0:1}]${base_name:1}")

    echo "$display"  # 返回结果（可能为空）
}

# 检查所有可能的X服务器
check_displays() {
    local uid=$1
    local display=""
    local value=""
    local servers=("Xwayland" "Xorg" "X")
    
    for server in "${servers[@]}"; do
        value=$(get_user_xdisplay "$uid" "$server")
        if [ -n "$value" ]; then
            display="$value"
            break 1
        fi
    done
    echo "${display}"
}

ONLINE_SEATS=
SESSIONSID=
showUser=$(getUser)
userID=`id -u ${showUser}`

EXPORT="export XDG_SESSION_TYPE=x11;"
EXPORT=${EXPORT}"export XDG_GREETER_DATA_DIR=/var/lib/lightdm/data/${showUser}; "
EXPORT=${EXPORT}"export XDG_RUNTIME_DIR=/run/user/${userID}; "
EXPORT=${EXPORT}"export XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0; "
EXPORT=${EXPORT}"export XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0; "
EXPORT=${EXPORT}"export XDG_SESSION_ID=${SESSIONSID}; "
EXPORT=${EXPORT}"export XDG_SEAT=${ONLINE_SEATS}; "
EXPORT=${EXPORT}"export XDG_SESSION_DESKTOP=deepin; " #uos
EXPORT=${EXPORT}"export XDG_CURRENT_DESKTOP=Deepin; " #uos

WAYLAND_SOCKET_DIR="/run/user/$userID"
wayland_socket=$(find "$WAYLAND_SOCKET_DIR" -maxdepth 1 -type s -name 'wayland-*' | head -n1)
if [ -n "$wayland_socket" ]; then
    EXPORT=${EXPORT}"export WAYLAND_DISPLAY=$(basename "$wayland_socket");"
fi

display=$(check_displays ${userID})
echo "check_displays = ${display}" >> /tmp/showui.log
if [ -z "$display" ]; then
	if pgrep -x "Xwayland" > /dev/null; then
		display=":0"
	else
		display=$(who | grep -- "$showUser" | awk 'NR==1 {gsub(/[()]/, "", $NF); print $NF}')
		if [ -z "$display" ]; then
			display=":0"
		fi
	fi
fi

echo "display = ${display}, showUser = ${showUser}" >> /tmp/showui.log
sudo -i -u $showUser -- bash -c "ls /tmp/ > /dev/null"

if [ $? -ne 0 ]; then
	if [[ "${DISPLAY}" == "" ]];then
		export DISPLAY=${display};
	fi
	echo "111111111111 DISPLAY = ${DISPLAY}" >> /tmp/showui.log
	${SHOWUI} $@
else
	echo "222222222222 display = ${display}" >> /tmp/showui.log
	sudo -i -u $showUser -- bash -c "${EXPORT} export DISPLAY=${display}; export LANGUAGE=zh_CN; export LANG=zh_CN.UTF-8; ${SHOWUI} \"\$@\"" -- "$@"
fi


