# filter and mount /backup 
function filter_and_mount() {
lsblk | while IFS= read -r line; do
  if [[ $line =~ ^([a-z]+)[[:space:]].*[[:space:]]([0-9.]+T)[[:space:]] ]]; then
    disk_name=${BASH_REMATCH[1]}
    disk_size=${BASH_REMATCH[2]}

    # 找到第一块大于3TB的盘
    if (( $(echo "$disk_size > 3" | bc -l) )); then
      echo "找到大于3TB的硬盘: $disk_name"

      # 检查是否存在分区
      partition_temp=$(lsblk -o NAME | grep -E "${disk_name}[0-9]$" | head -n 1 )
      partitions=$(echo ${partition_temp} | sed 's/[^a-zA-Z0-9]*//g')
      if [ -n "${partitions}" ]; then
        # 如果存在分区，挂载第一个分区
        partition=$(echo "$partitions" | head -n 1)
        mount_point="/BackUp"

        echo "挂载分区 /dev/$partition 到 $mount_point ..."
        sudo mount /dev/$partition $mount_point
        if [ $? -eq 0 ]; then
          echo "成功挂载硬盘到 $mount_point"
        else
          echo "挂载硬盘失败"
        fi
      else
        # 如果不存在分区，直接挂载硬盘
        mount_point="/BackUp"

        echo "挂载硬盘 /dev/$disk_name 到 $mount_point ..."
        sudo mount /dev/$disk_name $mount_point
        if [ $? -eq 0 ]; then
          echo "成功挂载硬盘到 $mount_point"
        else
          echo "挂载硬盘失败"
        fi
      fi

      # 停止循环，只处理第一块符合条件的盘
      break
    fi
  fi
done

}

# Check if the password complexity meets the requirements
function paswd_check() {
   password=$1
   if [[ ${#password} -lt 8 || ${#password} -gt 50 ]]; then
       echo "The password length must be greater than or equal to 8"
       return 1
   fi
   
   if ! echo "$password" | grep -q "[0-9]"; then
       echo "The password must contain at least one number"
       return 1
   fi
   
   if ! echo "$password" | grep -q "[A-Z]"; then
       echo "The password must contain at least one uppercase letter"
       return 1
   fi
   
   if ! echo "$password" | grep -q "[a-z]"; then
       echo "The password must contain at least one lowercase letter"
       return 1
   fi
   
   if ! echo "$password" | grep -q "[!@#\$%\^&\*\(\)-_+.,=]"; then
       echo "The password must contain at least one special character in this list [!@#\$%\^&\*\(\)-_+.,=]"
       return 1
   fi
   
   echo "Password meets the requirements"
}

# Check the number of parameter inputs
function param_check() {
   if [ $# -gt 1 ]; then
       echo "More than one input parameter"
       exit 1
   else
       echo "Parameter check meets requirements"
   fi
}

# Convert the input number into the corresponding operating system name
function num_change_to_vm_os() {
   num=$1
   case $num in
       1)  vm_os=ubuntu18
       ;;
       2)  vm_os=ubuntu20
       ;;
       3)  vm_os=win10
       ;;
       4)  vm_os=centos7
       ;;
       *)  echo 'You do not select a number between 1 to 4'
       ;;
   esac
}

# Check IP legality
function IP_check() {
    IP=$1
    IP_CHECK=$(echo $IP|awk -F. '$1<255&&$2<255&&$3<255&&$4<255{print "R"}')
    if echo $IP|grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" >/dev/null; then
    	if [ $IP_CHECK == "R" ]; then
    		echo "IP $IP  valid!"
    	else
    		echo "IP $IP invalid!"
		return 1
    	fi
    else
    	echo "IP $IP invalid!"
	return 1

    fi
}

#Convert numbers to binary digits
function D2B()
{
        num="$1"
        d2b=`echo "obase=2;$num" | bc`
        echo $d2b
}

# Check whether the entered subnet mask is legal
function check_subnet_mask()
{
        if [[ "$1" =~ ^[0-9]+$ ]]; then
           if [[ $1 -gt 8 && $1 -lt 33 ]];then
                   return 0
           else
		   return 1
           fi
	else
            echo $1 | grep "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" > /dev/null
            if [ $? = 1 ]; then
                    return 1
            fi
    
            a=`echo $1 | awk -F. '{print $1}'`
            b=`echo $1 | awk -F. '{print $2}'`
            c=`echo $1 | awk -F. '{print $3}'`
            d=`echo $1 | awk -F. '{print $4}'`
    
            a=`D2B $a`
            b=`D2B $b`
            c=`D2B $c`
            d=`D2B $d`
    
            for i in $a $b $c $d;do
                    [[ $i != 0 && ${#i} != 8 ]] && return 2
            done
            mask=$a$b$c$d
            [[ "$mask" =~ ^1[1]*[0]*$ ]] || return 3
    
            return 0
	fi
}


# Check if the GPU slot number input is legal
function check_gpu_slot_input() {
  local input="$1"

  if ! [[ "$input" =~ ^[0-9]+:[0-9]+\.[0-9]+$ ]]; then
    echo "invalid"
    return 1
  fi

  echo "valid"
  return 0
}

function clean_old_bak() {
# 定义目录路径
directory="$1"

# 获取该目录下的文件夹数量
folder_count=$(find "$directory" -maxdepth 1 -type d | wc -l)

# 检查文件夹数量是否大于等于3
if [ "$folder_count" -ge 3 ]; then
  # 获取当前目录下的所有文件夹，并按修改时间排序
  folders=$(find "$directory" -maxdepth 1 -type d -printf '%T@ %p\n' | sort -n | awk '{print $2}' | grep -v "$directory$")

  # 计算需要删除的文件夹数量,减去要保留的最老的1个，还有父文件夹本身
  delete_count=$((folder_count - 2))

  # 删除最旧的文件夹
  for folder in $folders; do
    if [ "$delete_count" -gt 0 ]; then
      rm -rf "$folder"
      delete_count=$((delete_count - 1))
    else
      break
    fi
  done
fi
}
function shutdown_vm() {
vm_name="$1"
flag_shutdown_time=1
while true
do
       if [ ${flag_shutdown_time} -eq 30 ];then
                echo "shutdown timeout, exec turn off"
                virsh destroy  $vm_name
                sleep 1s
                break
       fi
       virsh  shutdown $vm_name >/dev/null 2>&1
       vps_state=$(virsh domstate $vm_name  |grep -v "^$")
       if [ "${vps_state}" == "shut off" ]; then
               echo "${vm_name} shutdown successful"
               break
       fi
       sleep 1s
       (( flag_shutdown_time+=1 ))
       echo "Wait for the shutdown to complete..."
done
}
function time_format(){
    date "+%Y-%m-%d %H:%M:%S"
}

function clean_backup_log(){
    if [ ! -d "$clean_Backup_Log_Path" ]; then
        mkdir -p $clean_Backup_Log_Path
    fi
    echo "$@" >> $clean_Backup_Log_Path/clean_backup_log.`date "+%Y%m%d"`
}
function clean_bak(){
    oldest_folder=$(find "$backup_dir" -maxdepth 2 -type d -not -path "$backup_dir" -printf '%T+ %p\n' | sort |grep -v $exclude_file | head -n 1 | awk '{print $2}')
    clean_backup_log "$(time_format)"   "rm -rf  $oldest_folder"
    rm -rf $oldest_folder
}

