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

# 检查并创建目录
systemd_dir="/etc/systemd/system.conf.d"
user_dir="/etc/systemd/user.conf.d"
mkdir -p "$systemd_dir" "$user_dir"

systemd_override_file="$systemd_dir/98-deepin-debug-systemd_system.conf"
user_override_file="$user_dir/98-deepin-debug-systemd_user.conf"

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

update_or_delete_log_level() {
    local conf_file=$1:s
    local level=$2
    local override_file=$3

    # 检查日志级别是否设置为 'off'
    if [[ "$level" == "off" ]]; then
        # 如果日志级别设置为 'off'，删除 override 文件
        if [[ -f "$override_file" ]]; then
            rm -f "$override_file"
            echo "Logging override file has been removed."
        else
            echo "Logging override file does not exist."
        fi
    else
        # 如果日志级别不是 'off'，处理 override 文件
        if [[ ! -f "$override_file" ]]; then
            # 如果文件不存在，创建文件
            touch "$override_file"
        fi
        # 删除文件中所有的 LogLevel= 行
        sed -i '/^\s*LogLevel\s*=/d' "$override_file"
        # 添加新的 LogLevel 设置
        echo "LogLevel=$level" >> "$override_file"
        echo "LogLevel is set to '$level'."
    fi
}

# Process the input argument
case "${debug}" in
  "on")
    update_or_delete_log_level "system" "debug" "$systemd_override_file"
    update_or_delete_log_level "user" "debug" "$user_override_file"
    ;;
  "off" | "warning")
    update_or_delete_log_level "system" "off" "$systemd_override_file"
    update_or_delete_log_level "user" "off" "$user_override_file"
    ;;
  "debug" | "info" | "notice" | "err" | "crit" | "alert" | "emerg")
    update_or_delete_log_level "system" "$debug" "$systemd_override_file"
    update_or_delete_log_level "user" "$debug" "$user_override_file"
    ;;
  *)
    echo "Not support ${debug} parameter: $@"
    exit 1
    ;;
esac

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