#!/bin/bash

function show_sys_info() {
    local sys_name
    local distributor_id

    distributor_id=$(lsb_release -is)
    case ${distributor_id} in
    "Kylin" | "kylin" | "KYLIN")
        sys_name=$(cat /etc/os-release | grep PRETTY_NAME | awk -F "=" '{print $2}')
        ;;
    "Uos" | "UOS" | "uos")
        local version
        version=$(cat /etc/os-version | grep MinorVersion | awk -F "=" '{print $2}')
        sys_name="UOS ${version}"
        ;;
    esac

    local sys_info
    sys_info=$(uname -a)

    echo -e "系统名称：${sys_name}\n系统信息：${sys_info}"

}

function get_current_login_name() {

  local user_name=""
  declare -A property
  for session in $(loginctl --no-legend list-sessions | awk '{ print $1 }'); do

    while IFS="=" read key value; do
      property[${key}]="${value}"
    done < <(loginctl show-session "${session}")

    if [ "${property[Type]}" = "x11" ] || [ "${property[Type]}" = "wayland" ]; then
      user_name=${property[Name]}
      if [ "${property[Active]}" = "yes" ]; then
        break
      fi
    fi
  done

  if [ "${user_name}" == "" ] || [ "${user_name}" == "root" ]; then
    echo ""
    return 1
  fi

  echo "${user_name}"
  return 0
}

function readini() {
  if [ $# -lt 2 ];then
     echo 'Usage:readini.sh <.ini file> <section> [<key>] [<newvalue>]'
     exit 1
  fi
  if [ "$3" = "" ];then
    sed -n "/\[$2\]/,/\[.*\]/{
    /^\[.*\]/d
    /^[ ]*$/d
    s/;.*$//
    p
    }" "$1"
  elif [ "$4" = "" ];then
    sed -n "/\[$2\]/,/\[.*\]/{
    /^\[.*\]/d
    /^[ ]*$/d
    s/;.*$//
    s/^[ |\t]*$3[ |\t]*=[ |\t]*\(.*\)[ |\t]*/\1/p
    }" "$1"
  else
    if [ "$4" = "#" ];then
      sed "/\[$2\]/,/\[.*\]/{
      s/^[ |\t]*$3[ |\t]*=.*/ /
      }" "$1" > /tmp/sed$$
      cat /tmp/sed$$ > "$1" # 避免修改文件属性
      rm /tmp/sed$$
    else
      sed "/\[$2\]/,/\[.*\]/{
      s/^[ |\t]*$3[ |\t]*=.*/$3=$4/
      }" "$1" > /tmp/sed$$
      cat /tmp/sed$$ > "$1"
      rm /tmp/sed$$
    fi
  fi
}

function re_config_kwinrc() {
    local file
    file="$1"

    readini "${file}" Compositing Enabled true
    readini "${file}" Compositing Backend OpenGL
    readini "${file}" Compositing OpenGLIsUnsafe false
}

function re_config_all_kwinrc() {

  local files=(
  "/etc/xdg/kwinrc"
  "/etc/xdg/ukui-kwinrc"
  )
  while read -r homedir; do
    if [ "$(realpath "${homedir}")" != "/" ]; then
      files=("${files[@]}"
       "${homedir}/.config/kwinrc"
       "${homedir}/.config/ukui-kwinrc")
    fi
  done <<< "$(grep -vE "nologin$" /etc/passwd |grep -vE "false$" |awk -F ":" '{print $6}')"

  for file in "${files[@]}"; do
    [ -f "$file" ] && re_config_kwinrc "$file"
  done
}

function get_desktop() {
    local desktop_env
    local distributor_id

    distributor_id=$(lsb_release -is)
    case ${distributor_id} in
    "Kylin" | "kylin" | "KYLIN")
        desktop_env="ukui"
        ;;
    "Uos" | "UOS" | "uos")
        desktop_env="kde"
        ;;
    * )
        return 1
    esac

    echo ${desktop_env}
    return 0
}

function reload_watermark() {
    local desktop_env
    if ! desktop_env=$(get_desktop); then
        echo "不支持的桌面：${desktop_env}"
        return 1
    fi

    dbus_cmd="dbus-send --type=signal --dest=org.${desktop_env}.KWin /Compositor org.${desktop_env}.kwin.Compositing.reinit"

    local user_name
    user_name=$(get_current_login_name)
    su -m "${user_name}" -c "${dbus_cmd}"
}

function open_watermark() {

    [ -f /etc/xdg/LowPerformanceCPU.list ] && mv /etc/xdg/LowPerformanceCPU.list /etc/xdg/LowPerformanceCPU_back.list
    [ -f /etc/xdg/LowVgaPci.list ] && mv /etc/xdg/LowVgaPci.list /etc/xdg/LowVgaPci_back.list

    cat >/etc/X11/Xsession.d/05uos-sangfor-uem-profile <<EOF
echo "KWIN_COMPOSE:$KWIN_COMPOSE"
unset KWIN_COMPOSE
echo "KWIN_COMPOSE:$KWIN_COMPOSE"
EOF

    re_config_all_kwinrc

    reload_watermark

    echo "已尝试强制开启应用级水印, 注销电脑用户或重启后生效"
}

function close_watermark() {

    [ -f /etc/xdg/LowPerformanceCPU_back.list ] && mv /etc/xdg/LowPerformanceCPU_back.list /etc/xdg/LowPerformanceCPU.list
    [ -f /etc/xdg/LowPerformanceCPU.list.back ] && mv /etc/xdg/LowPerformanceCPU.list.back /etc/xdg/LowPerformanceCPU.list
    [ -f /etc/xdg/LowVgaPci_back.list ] && mv /etc/xdg/LowVgaPci_back.list /etc/xdg/LowVgaPci.list
    [ -f /etc/xdg/LowVgaPci.list.back ] && mv /etc/xdg/LowVgaPci.list.back /etc/xdg/LowVgaPci.list

    [ -f /etc/X11/Xsession.d/05uos-sangfor-uem-profile ] && rm /etc/X11/Xsession.d/05uos-sangfor-uem-profile

    reload_watermark
    echo "已将配置还原为初始状态， 注销电脑用户或重启后生效"
}

function check_watermark() {
    # 配置环境变量
    local user_name
    local user_id
    local dbus_path
    if ! user_name=$(get_current_login_name); then
        echo "获取当前用户失败"
        return 1
    fi
    user_id=$(id -u "${user_name}")
    dbus_path="unix:path=/run/user/${user_id}/bus"
    export DBUS_SESSION_BUS_ADDRESS=${dbus_path}

    # 检测合成器类型，需要以普通用户权限连接dbus
    local dbus_cmd_prefix
    local dbus_compositor_cmd
    local dbus_effects_cmd
    local desktop_env
    if ! desktop_env=$(get_desktop); then
        echo "不支持的桌面：${desktop_env}"
        return 1
    fi

    dbus_cmd_prefix="dbus-send --session --type=method_call --print-reply=literal --dest=org.${desktop_env}.KWin"
    dbus_compositor_cmd="${dbus_cmd_prefix} /Compositor org.freedesktop.DBus.Properties.Get string:\"org.${desktop_env}.kwin.Compositing\" string:\"compositingType\" | awk -F \" \" '{print \$2}'"

    local compositor_type
    compositor_type=$(su -m "${user_name}" -c "${dbus_compositor_cmd}")

    echo "合成器类型: ${compositor_type}"
    local watermark_info="应用级水印已配置:"
    if [ "${compositor_type}" != "gl2" ]; then
        echo ${watermark_info} "否"
        return 1
    fi

    # 检测特效是否开启，需要以普通用户权限连接dbus
    local effects
    dbus_effects_cmd="${dbus_cmd_prefix} /Effects org.freedesktop.DBus.Properties.Get string:\"org.${desktop_env}.kwin.Effects\" string:\"activeEffects\""
    if ! effects=$(su -m ${user_name} -c "${dbus_effects_cmd}"); then
        echo ${watermark_info} "否"
        return 1
    fi

    echo ${watermark_info} "是"
    return 0
}

function main() {

    show_sys_info
    check_watermark

    while :
    do
        local flag=
        echo "----------------------------------------"
        echo -e "尝试强制开启应用级水印请输入：\t\ty"
        echo -e "根据硬件条件判断水印模式请输入：\tn"
        echo -e "退出请输入：\t\t\t\tq"

        read -r flag

        case ${flag} in
        "Y" | "y")
           open_watermark
           break;;
        "N" | "n")
            close_watermark
            break;;
        "Q" | "q")
            break;;
        * )
            echo "无效参数: ${flag}, 请重新输入."
        esac
    done
}

if [ ${USER} != "root" ]; then
    sudo bash "$(realpath $0)" "$@"
else
    main "$@"
fi