#!/bin/bash
source /root/vm-tool/vm_functions.sh
#set -x
Backup_Dir="/BackUp"
Backup_Log_Path="/root/vm-tool/log"
Vm_List=$(virsh list --all |sed '/^$/d'|awk 'NR>2{print $2}')

file_name="/root/linux_exclude_vps_name.txt"
declare -a exclude_list=()
if [[ -f $file_name ]]; then
  exclude_list=($(cat $file_name))
fi
function is_new_dbm_panel() {
  vps=$1
#   echo $vps
  flag="0"
  for line in "${exclude_list[@]}"; do
      if [ "$line" == "$vps" ]; then
          flag="1"
          break
      fi
  done
  if [[ $flag == "1" ]]; then
    return 0
  else
    return 1
  fi
}

function time_format {
	date "+%Y-%m-%d %H:%M:%S"
}

function half_month_backup_log {
	if [ ! -d "$Backup_Log_Path" ]; then
		mkdir -p $Backup_Log_Path
	fi
	echo "$@" >> $Backup_Log_Path/half_month_backup_log.`date "+%Y%m%d"`
}

function half_month_backup {
for vm_name in $Vm_List
do
	if [[ $vm_name == vps_* ]]; then
        continue 
    fi

	if is_new_dbm_panel $vm_name; then
        continue 
    fi
        
    echo $vm_name
	Vm_Mem=$(virsh dumpxml ${vm_name} |grep currentMemory|awk -F ">" '{print $2}'|awk -F "<" '{print $1}')
	if [ `echo "$Vm_Mem > 30000000" |bc` -eq 1 ]; then
		half_month_backup_log "`time_format` $vm_name starting backup"
                Disk_Path=$(virsh dumpxml $vm_name|grep "source file" | grep -v "seed" |awk -F "'" '{print $2}')
                Data_Dir=${Disk_Path%/*}
                Date=$(date +%Y%m%d%H%M%S)
		dest_backup_path=/BackUp/$vm_name.cancelled_reserve
		if [[ ! -d "$dest_backup_path" ]]; then
			mkdir -p $dest_backup_path
		else
			clean_old_bak $dest_backup_path
		fi
                cp -r $Data_Dir /BackUp/$vm_name.cancelled_reserve/${vm_name}_$Date
                virsh dumpxml $vm_name > /BackUp/$vm_name.cancelled_reserve/${vm_name}_$Date/$vm_name.xml_$Date		
		BackUp_Size=$(ls -lh /BackUp/$vm_name.cancelled_reserve/${vm_name}_$Date/$vm_name.qcow2 |awk '{print $5}')
                ori_disk_Size=$(ls -lh $Disk_Path |awk '{print $5}')
		
		diff=$(echo "${BackUp_Size%G} - ${ori_disk_Size%G}" | bc -l)
                abs_diff=$(echo "if ($diff<0) -($diff) else $diff" | bc -l)

               if [ -f "/BackUp/$vm_name.cancelled_reserve/${vm_name}_$Date/$vm_name.qcow2" ] && [ -f "/BackUp/$vm_name.cancelled_reserve/${vm_name}_$Date/$vm_name.xml_$Date" ] && [ $(echo "$abs_diff < 2" | bc -l) ]; then
			half_month_backup_log "`time_format` $vm_name backup successed! Backup files szie: $Backup_Size"
		else
			half_month_backup_log "`time_format` $vm_name backup failed! Please check it"
		fi
	else
		echo  "$vm_name use other backup periods"
	fi
done
}
filter_and_mount
half_month_backup_log "`date "+%Y-%m-%d"` Starting backup tasks"
half_month_backup
umount ${Backup_Dir}

