#!/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

module_name="coredump"
if [ $# -ne 1 ]; then
    echo "Invalid argument"
    exit 1
fi
# 判断输入参数是否在输入参数的范围中
arg_ranges=("on" "off")
if [[ ! " ${arg_ranges[*]} " =~ " $1 " ]]; then
    echo "ERROR: Invalid argument for configuring ${pkg_name} debug mode"
    exit 1
fi

debug_package="systemd-coredump"
coredump_config="/etc/systemd/coredump.conf"
coredump_config_default="/etc/systemd/coredump.conf.bak-off-debug"
# 获取当前用户的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

# 备份coredump_config
backup_default_coredump_config() {
    if [[ ! -f "$coredump_config_default" ]]; then
        if [[ ! -f "$coredump_config" ]]; then
          echo "$coredump_config does not exist"
          return 0
        fi
        cp "$coredump_config" "$coredump_config_default"
    fi
    sed -i "/^\s*Storage=none/d" "$coredump_config_default"
}


# 不管开不开启coredump都去安装systemd-coredump
# 判断systemd-coredump是否已经安装
dpkg -l "${debug_package}" &>/dev/null
if [ $? -eq 0 ]; then
  echo "${debug_package} already installed"
else
# 安装systemd-coredump
  package_version=$(dpkg -s systemd | grep '^Version' | awk '{print $2}')
  if [ -z "$package_version" ]; then
    echo "Cannot find package_version for systemd"
    return 1
  fi
  apt-get install -y "${debug_package}=${package_version}"
  if [ $? -ne 0 ]; then
    echo "Failed to install ${debug_package}=${package_version}"
    exit 1
  fi
fi

if [[ ! -f "$coredump_config" ]]; then
  echo "$coredump_config does not exist"
  exit 0
fi

# Process the input argument
case "$1" in
  "on")
    if [[ ! -f "$coredump_config" ]]; then
        echo "Failed to find $coredump_config"
        exit 1
    fi
    if [[ $(grep -cE '^\s*Storage=' "$coredump_config") -eq 0 ]]; then
        echo "Coredump are already enabled."
    else
        backup_default_coredump_config
        # 删除含有Storage=none的行,此时coredump默认是打开的
        sed -i "/^\s*Storage=none/d" "$coredump_config"
        # 因为systemd-coredump服务是需要core时才会启动，所以只需要重新加载配置文件
        systemctl daemon-reload
        echo "Coredump are enabled."
    fi
    ;;
  "off")
    if [[ $(grep -cE '^\s*Storage=none' "$coredump_config") -gt 0 ]]; then
        echo "Coredump are already disabled."
    else
        # 删除含有Storage=的行
        sed -i "/^\s*Storage=/d" "$coredump_config"
        echo "Storage=none" >> "$coredump_config"
        # 因为systemd-coredump服务是需要core时才会启动，所以只需要重新加载配置文件
        systemctl daemon-reload
        echo "Coredump are disabled."
    fi
    ;;
esac