#!/bin/bash
# A script to configure the module's debug log level.
# 
# Note: Please do not modify this script directly, 
# as modifying this script will invalidate this script.
set -e

pkg_name="qt"
debug="no"

# 获取当前用户的UID
current_uid=$(id -u)

# 判断是否是Root权限
if [ "$current_uid" -ne 0 ]; then
  echo "You need to have root privileges to run this script."
  exit 1
fi

qt_env_file="/etc/X11/Xsession.d/00deepin-dde-env"
qt_env_file_backup_nodebug="/etc/X11/Xsession.d/00deepin-dde-env.bak-off-debug"

if [ ! -f  "$qt_env_file" ]; then
    echo "ERROR: Cannot find ${qt_env_file}"
    exit 1
fi


# 找到QT_LOGGING_RULES所在的行号
line_number=$(grep -n 'QT_LOGGING_RULES' "$qt_env_file" | cut -d':' -f1)
if [ ! -n "$line_number" ]; then
    echo "ERROR: Cannot find QT_LOGGING_RULES in ${qt_env_file}"
    exit 1
fi

for x in "$@"; do
        case $x in
        debug=*)
                debug=${x#debug=}
                ;;
        esac
done

# 备份qt_env_file
backup_no_debug_qt_env_file() {
    if [[ ! -f "$qt_env_file_backup_nodebug" ]]; then
        cp "$qt_env_file" "$qt_env_file_backup_nodebug"
    fi
    sed -i "${line_number}s/export QT_LOGGING_RULES=\"\*\.debug=true/export QT_LOGGING_RULES=\"\*\.debug=false/" "$qt_env_file_backup_nodebug"
    sed -i "${line_number}s/\*\.info=true/\*\.info=false/" "$qt_env_file_backup_nodebug"
}

case "${debug}" in
  "on" | "debug")
    if [[ $(grep -cE 'export QT_LOGGING_RULES=\"\*\.debug=true' "$qt_env_file") -gt 0 ]]; then
        sed -i "${line_number}s/\*\.info=false/\*\.info=true/" "$qt_env_file"
        echo "Debug logs are already enabled for ${pkg_name}."
    else
        backup_no_debug_qt_env_file
        sed -i "${line_number}s/export QT_LOGGING_RULES=\"\*\.debug=false/export QT_LOGGING_RULES=\"\*\.debug=true/" "$qt_env_file"
        sed -i "${line_number}s/\*\.info=false/\*\.info=true/" "$qt_env_file"
        echo "Debug logs are enabled for ${pkg_name}. "
    fi
    ;;
  "off" | "warning")
    # if [ -f "$qt_env_file_backup_nodebug" ]; then
    #     cp "$qt_env_file_backup_nodebug" "$qt_env_file"
    # fi
    if [[ $(grep -cE 'export QT_LOGGING_RULES=\"\*\.debug=false' "$qt_env_file") -gt 0 ]]; then
        sed -i "${line_number}s/\*\.info=true/\*\.info=false/" "$qt_env_file"
        echo "Debug logs are already disabled for ${pkg_name}."
    else
        sed -i "${line_number}s/export QT_LOGGING_RULES=\"\*\.debug=true/export QT_LOGGING_RULES=\"\*\.debug=false/" "$qt_env_file"
        sed -i "${line_number}s/\*\.info=true/\*\.info=false/" "$qt_env_file"
        echo "Debug logs are disabled for ${pkg_name}."
    fi
    ;;
  *)
    echo "Not support ${debug} parameter: $@"
    exit 1;
    ;;
esac
