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

bluetooth_sh_file="/usr/lib/bluetooth/bluetoothd.sh"
bluetooth_sh_file_backup_nodebug="/usr/lib/bluetooth/bluetoothd.sh.bak-off-debug"
bluetoothd="/usr/lib/bluetooth/bluetoothd"

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

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

# 备份bluetooth_sh_file
backup_no_debug_bluetooth_sh_file() {
    if [[ ! -f "$bluetooth_sh_file_backup_nodebug" ]]; then
        cp "$bluetooth_sh_file" "$bluetooth_sh_file_backup_nodebug"
    fi
    sed -i "s/\/usr\/lib\/bluetooth\/bluetoothd -d/\/usr\/lib\/bluetooth\/bluetoothd/" "$bluetooth_sh_file_backup_nodebug"
}

case "${debug}" in
  "on" | "debug")
    if [[ $(grep -cE '/usr/lib/bluetooth/bluetoothd -d' "$bluetooth_sh_file") -gt 0 ]]; then
        echo "Debug logs are already enabled for ${pkg_name}."
    else
        backup_no_debug_bluetooth_sh_file
        sed -i "s/\/usr\/lib\/bluetooth\/bluetoothd/\/usr\/lib\/bluetooth\/bluetoothd -d/" "$bluetooth_sh_file"
        echo "Debug logs are enabled for ${pkg_name}."
    fi
    ;;
  "off" | "warning")
    if [[ $(grep -cE '/usr/lib/bluetooth/bluetoothd -d' "$bluetooth_sh_file") -eq 0 ]]; then
        echo "Debug logs are already disabled for ${pkg_name}."
    else
        # if [ -f "$backup_no_debug_bluetooth_sh_file" ]; then
        #     cp "$backup_no_debug_bluetooth_sh_file" "$bluetooth_sh_file"
        # fi
        sed -i "s/\/usr\/lib\/bluetooth\/bluetoothd -d/\/usr\/lib\/bluetooth\/bluetoothd/" "$bluetooth_sh_file"
        echo "Debug logs are disabled for ${pkg_name}."
    fi
    ;;
  *)
    echo "Not support ${debug} parameter: $@"
    exit 1;
    ;;
esac
