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

SHOWUI="/opt/apps/com.ftsafe.interpass3000-gdrc/files/bin/showUI_GDRC_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  
	showUser=${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"  # 返回结果（可能为空）
}

check_system() {
    local info=""

    # 优先读取标准文件
    if [ -f /etc/os-release ]; then
        info=$(cat /etc/os-release)
    elif [ -f /usr/lib/os-release ]; then
        info=$(cat /usr/lib/os-release)
    else
        # 退回到 issue / release 文件
        info=$(cat /etc/issue 2>/dev/null || cat /etc/*-release 2>/dev/null)
    fi

    # 转小写，统一处理
    info=$(echo "$info" | tr '[:upper:]' '[:lower:]')

    if echo "$info" | grep -q "uos\|uniontech"; then
        echo "UOS"
    elif echo "$info" | grep -q "kylin\|neokylin"; then
        echo "Kylin"
    else
        echo ""
    fi
}

# 检查所有可能的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}; "

if [[ "$(check_system)" == "UOS" ]]; then
	echo "system is UOS" >> /tmp/showui.log
	EXPORT=${EXPORT}"export XDG_SESSION_DESKTOP=deepin; " #uos
	EXPORT=${EXPORT}"export XDG_CURRENT_DESKTOP=Deepin; " #uos
elif [[ "$(check_system)" == "Kylin" ]]; then
	echo "system is Kylin" >> /tmp/showui.log
	mate=`ps -ef | grep mate-session | grep -v grep | awk '{printf $2}'`
	if [ 'x'${mate} == 'x' ]; then #kylin
		EXPORT=${EXPORT}"export XDG_SESSION_DESKTOP=ukui; " #kylin
		EXPORT=${EXPORT}"export XDG_CURRENT_DESKTOP=UKUI; " #kylin
	else #kylin
		EXPORT=${EXPORT}"export XDG_SESSION_DESKTOP=mate; " #kylin
		EXPORT=${EXPORT}"export XDG_CURRENT_DESKTOP=MATE; " #kylin
	fi #kylin
else
	echo "system is unknown" >> /tmp/showui.log
fi


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}, SHOWUI = ${SHOWUI}" >> /tmp/showui.log
sudo -i -u $showUser -- bash -c "ls /tmp/ > /dev/null"

if [ $? -ne 0 ]; then
	${EXPORT}
	export DISPLAY=${display};
	export LANGUAGE=zh_CN;
	export LANG=zh_CN.UTF-8; 
	echo "111111, DISPLAY = ${DISPLAY}" >> /tmp/showui.log
	${SHOWUI} $@
else
	echo "22222, 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

