#!/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="pulseaudio"
debug_level="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

# 配置文件目录和文件
conf_dir="/etc/pulse/daemon.conf.d"
override_file="$conf_dir/99-deepin-debug-config.conf"

# 确保配置目录存在
mkdir -p "$conf_dir"

# 更新或创建 override 文件
update_override_file() {
    local level=$1

    # 如果设置为 off，则删除 log-level 配置行
    if [[ "$level" == "off" ]]; then
        # 如果文件存在，删除 log-level 配置行
        if [[ -f "$override_file" ]]; then
            rm -f "$override_file"
            # sed -i '/^\s*log-level\s*=/d' "$override_file"
            # # 如果文件为空，则删除文件
            # if [[ ! -s "$override_file" ]]; then
            #     rm -f "$override_file"
            # fi
        fi
    else
        # 删除现有的 log-level 行
        # if [[ -f "$override_file" ]]; then
        #     sed -i '/^\s*log-level\s*=/d' "$override_file"
        # fi

        # 创建或更新 override 文件
        # echo "[logging]" > "$override_file"
        echo "log-level = $level" > "$override_file"
    fi

    # 重新加载 PulseAudio 配置
    # systemctl --user daemon-reload
    # pulseaudio -k
    # pulseaudio --start
}

# 处理输入参数
for x in "$@"; do
    case $x in
        debug=*)
            debug_level=${x#debug=}
            ;;
    esac
done

# 根据参数设置日志级别
case "${debug_level}" in
    "on" | "debug" | "info" | "notice" | "err" | "crit" | "alert" | "emerg")
        update_override_file "$debug_level"
        ;;
    "off" | "warning")
        update_override_file "off"
        ;;
    *)
        echo "Not support ${debug_level} parameter: $@"
        exit 1
        ;;
esac

echo "Debug logs are set to '${debug_level}' for ${pkg_name}."