#!/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="network-manager"
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/NetworkManager/conf.d"
override_file="$conf_dir/99-deepin-debug-config.conf"

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

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

    # 如果 level 设置为 off，则删除 override 文件
    if [[ "$level" == "off" ]]; then
        if [[ -f "$override_file" ]]; then
            rm -f "$override_file"           
        fi
        echo "NetworkManager debug mode has been turned off."
    else
        # 如果 override 文件存在，则删除现有的 level= 行
        if [[ -f "$override_file" ]]; then
            sed -i '/^\s*level=/d' "$override_file"
        fi

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

        # 重新加载 NetworkManager 配置
        # systemctl reload NetworkManager
    fi
}

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

# 根据参数设置日志级别
case "${debug_level}" in
    "on" | "debug")
        update_override_file "TRACE"
        ;;
    "off" | "warning")
        update_override_file "off"
        ;;
    "TRACE" | "DEBUG" | "INFO" | "WARN" | "ERR" | "OFF")
        update_override_file "$debug_level"
        ;;
    *)
        echo "Not support ${debug_level} parameter: $@"
        exit 1
        ;;
esac

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