#!/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
#set -x
if [ $# -ne 1 ]; then
    echo "Invalid argument"
    exit 1
fi

dbgconf="/usr/share/deepin-debug-config/deepin-debug-config.d/dbg.conf"
get_from_dbg_source=0
# 获取当前用户的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

function install_dbg {
  package_name=$1
  count=0
  echo "Start to install dbgsym packages for ${package_name}"
  #echo $package_name
  # Get list of installed packages
  package_version=$(dpkg -s "${package_name}" | grep '^Version' | awk '{print $2}')
  if [ -z "$package_version" ]; then
    echo "Cannot find package_version for ${package_name}"
    return 1
  fi
  if [ -f "$dbgconf" ]; then
	  apt update -c $dbgconf
	  if [ $? -eq 0 ]; then
		  get_from_dbg_source=1
	  fi
  fi
  # echo "${package_version}"
  deb_pkgs=$(dpkg -l | grep '^ii' | grep -w "${package_version}" | awk '{print $2}' | cut -d ':' -f 1 | grep -v dbgsym | tr '\n' ' ')
  #echo ${deb_pkgs}
  pkg_array=($deb_pkgs)
  num_pkgs=${#pkg_array[@]}
  echo "Number of packages: $num_pkgs"
  # 循环安装调试包
  for package in $deb_pkgs
  do
    debug_package="${package}-dbgsym"
    echo "Installing ${debug_package}..."

    # 判断调试包是否已经安装
    dpkg -l "${debug_package}" &>/dev/null
    if [ $? -eq 0 ]; then
      echo "${debug_package} already installed"
      continue
    fi

    #安装调试包
    if [ $get_from_dbg_source -eq 1 ]; then
    	apt-get install -c $dbgconf -y "${debug_package}=${package_version}"
	if [ $? -eq 0 ]; then
		echo "${debug_package} install from dbg source sucess!"
		continue;
	fi
    fi
    echo "${debug_package} install from dbg source failed,now try to install from main source!"
    apt-get install -y "${debug_package}=${package_version}"
    if [ $? -ne 0 ]; then
	    ((count++))
	    echo "Failed to install ${debug_package}=${package_version}"
    fi
  done
  # 所有要安装的调试包均安装失败
  if [ $count -eq $num_pkgs ]; then
    return 1;
  fi
}

install_dbg $@
