#!/bin/bash

echo $*

XGS=false

INFO="/etc/.bootinfo"
METAINFO=".METAINFO"
KB=1024
MB=1048576
GB=1073741824

if [ $# -lt 3 ]; then
    exit 18
fi

#是否有/data数据分区
hasDataPartition=0
backupORrestore=$1
rootpath=$2
m_mountPath=$3
m_default_uuid=$4

# m_backuplistPath="${m_mountPath}/snapshots/backuplist.xml"
m_backuplistPath="${m_mountPath}/snapshots/sys_update_backuplist.xml"
EXCLUDEFILE="${m_mountPath}/snapshots/.exclude"
PLOGFILEDIR="${m_mountPath}/log"
PLOGFILE="$PLOGFILEDIR/log-$(date +%Y%m%d%H%M)"
LOGFILE="${m_mountPath}/log.txt" #LOGFILE="/tmp/log.txt"

#是否是出厂备份
m_isFactory=false
factory_uuid="00000000-0000-0000-0000-000000000000"
auto_uuid="01234567-0123-0123-0123-0123456789ab"
PERSONAL_EXCLUDEFILE=".exclude.user.txt"
PERSONAL_BACKUPFILE=".user.txt"
m_isRetainUserData=false
m_PrefixDestPath=""
m_Position=false

#如果/backup不存在，则创建该目录
mkdir -p ${m_mountPath}
if [ $? -ne 0 ]; then
    echo "Could not create /backup in initrd!"
    exit 20
fi
m_restoreUuid=""
m_enabled=""
global_system_usedDisk=0
m_size=0
newSize=0

#-----------------------------------------------------------------
get_is_990_9a0() {
    local ret=false
    # 匹配 kirin 990 5g, kirin990, kirin 9006c
    if egrep -qi 'kirin.?9[09]0' /proc/cpuinfo; then
        ret=true
    elif egrep -qi 'PANGU' /proc/cpuinfo; then
	ret=true

    fi
    echo $ret
}
is_990_9a0=$(get_is_990_9a0)

getBackupInfo() {
    if [ "$rootpath" = "/" ]; then
        bootinfo=$INFO
    else
        bootinfo=${rootpath}${INFO}
    fi

    if [ ! -e "$bootinfo" ]; then
	# 系统崩坏，如操作失误删除了/etc目录
        if [ -e $INFO ]; then
            bootinfo=$INFO
        else
            echo "$bootinfo file not exist!"
            m_restoreUuid=""
            return
        fi
    fi

    which_line=0
    content=$(cat "$bootinfo" | grep -Ev "^#" | grep "=" | awk '{print $1}')
    for line in $content; 
    do
        #parse_device "$device"
        #只读第1行：RECOVERY_DEV_UUID=c965e712-9903-4139-b8da-c6e1eef0af6a
        if [ $which_line -eq 0 ]; then
            m_restoreUuid=$(echo $line | sed 's:.*=::' | tr -d "\n")
            which_line=$(expr $which_line + 1)
        else
            m_enabled=$(echo $line | sed 's:.*=::' | tr -d "\n")
            which_line=$(expr $which_line + 1)
        fi
    done
}

#-----------------------------------------------------------------

#该函数是对backup-daemon/parsebackuplist.cpp中相应函数的替换
createBackupList() {
    local backuplistDir="${m_mountPath}/snapshots/"

    if [ ! -e "$backuplistDir" ]; then
        mkdir -p $backuplistDir
    fi

    if [ ! -e "$m_backuplistPath" ]; then

        #第1行'>'会清空后写文件
        echo "<?xml version='1.0'?>" >$m_backuplistPath
        echo "<backupList/>" >>$m_backuplistPath
    fi
}

#-----------------------------------------------------------------

mountBackup() {

	# 无备份分区时
	if [ "${m_restoreUuid}xy" = "xy" ]; then
    	echo "No backup partation. Log for backuping and restoring...."
		mount -o defaults,bind  ${rootpath}/backup ${m_mountPath}
		sleep 1
	else
		local myuuid="/dev/disk/by-uuid/${m_restoreUuid}"

    	tmp_root_dev=$(mount | grep " /root " | cut -d ' ' -f 1)
    	case "$tmp_root_dev" in
    		/dev/mapper/*)
        		eval $(dmsetup splitname --nameprefixes --noheadings --rows "${tmp_root_dev#/dev/mapper/}")
        		if [ "$DM_VG_NAME" ] && [ "$DM_LV_NAME" ]; then
            			lvm lvchange -aay -y --sysinit --ignoreskippedcluster "$DM_VG_NAME"
        		fi
        		;;
    	esac

    	mount -o defaults,rw -U $m_restoreUuid $m_mountPath
    	if [ $? -ne 0 ]; then
        	echo "Mount backup failed!"
        	exit 21
    	fi
	fi

    mkdir -p $PLOGFILEDIR
    if [ $? -ne 0 ]; then
        echo "Could not create log directory in /backup"
        exit 22
    fi

    touch $PLOGFILE
    if [ $? -ne 0 ]; then
        echo "Could not create log file"
        exit 23
    fi
    echo "Log for backuping and restoring...." >$PLOGFILE
    createBackupList #创建备份信息
}

#-----------------------------------------------------------------

umountBackup() {
    umount $m_mountPath
}

#-----------------------------------------------------------------

parse_device() {
    device=$1
    if echo $device | grep -E -q "^UUID="; then
        echo $device | sed 's:^UUID=:/dev/disk/by-uuid/:' | tr -d "\n"
    elif echo $device | grep -E -q "^LABEL="; then
        echo $device | sed 's:^LABEL=:/dev/disk/by-label/:' | tr -d "\n"
    else
        echo $device | tr -d "\n"
    fi
}

is_remote() {
    fstype=$1
    if [ nfs = "$fstype" ] || [ nfs4 = "$fstype" ] || [ smbfs = "$fstype" ] || [ cifs = "$fstype" ] || [ coda = "$fstype" ] || [ ncp = "$fstype" ]; then
        echo yes
    elif [ ncpfs = "$fstype" ] || [ ocfs2 = "$fstype" ] || [ gfs = "$fstype" ] || [ gfs2 = "$fstype" ] || [ ceph = "$fstype" ]; then
        echo yes
    else
        echo no
    fi
}

writeLogFile() {
    echo $1 >>$LOGFILE
}

CreateUuid() {
	local uuid=`cat /proc/sys/kernel/random/uuid|tr -d "\n"`
	while [ "$uuid" = $factory_uuid -o "$uuid" = $auto_uuid ]
    do
    	uuid=`cat /proc/sys/kernel/random/uuid|tr -d "\n"`
    done
    echo $uuid
}

#返回值：
getLastUsefulBackupPointUuid() {
    local xxx=""
    local currentUuid=""
    local currentState=false
    local currentType=true
    lastUsefulBackupPointUuid=""
    foundComment=0 #是否发现了要修改的comment
    local currentComment=""
    lastbackupname=""
    local backupPositionMode=false
    local backupPrefixDestPath=""
    #如果不定义IFS，则echo $line会去掉前后空格，导致写到文件中去时没有格式
    IFS_old=$IFS
    IFS=$'\n'
    while read line; do
        #去除了前后空格
        xxx=$(echo "$line" | sed "s/^[ \t]*//g" | sed "s/[ \t]*$//g")
        #echo "xxx: $xxx"
       
	if [[ "$xxx" =~ "<Comment>" ]]; then
	    currentComment=$xxx
	fi

        if [[ "$xxx" =~ "<Uuid>" ]]; then
            echo "uuid=${xxx} , m_default_uuid = ${m_default_uuid}" >>$PLOGFILE
            currentUuid=${xxx}
            currentState=false
            currentType=true
	        backupPositionMode=false
	        backupPrefixDestPath=""
        fi

        if [[ "$xxx" =~ "<State>backup finished</State>" ]]; then
            currentState=true
        fi

        if [[ "$xxx" =~ "<Type>2</Type>" ]]; then
            currentType=false
        fi

        if [[ "$xxx" =~ "<Type>3</Type>" ]]; then
            currentType=false
        fi

	if [[ "$xxx" =~ "<Position>3</Position>" ]]; then
        #    currentType=false
	    backupPositionMode=true
    fi

	if [[ "$xxx" =~ "<PrefixDestPath>" ]]; then
		backupPrefixDestPath=${xxx#<PrefixDestPath>}
		backupPrefixDestPath=${backupPrefixDestPath%</PrefixDestPath>}
		# if [[ x"$backupPrefixDestPath" = x"" || "$backupPrefixDestPath" = "/" || $backupPrefixDestPath =~ ^/data || $backupPrefixDestPath =~ ^/autobackup ]]; then
        if [[ ! $backupPrefixDestPath =~ ^/media/ ]]; then
			backupPositionMode=true
		else
			currentType=false
		fi
	fi

    if [[ "$xxx" =~ "</BackupPoint>" ]]; then
        if [ "$currentState" = "true" -a "$currentType" = "true" ]; then #"/backup"是不是一个独立的盘
            lastUsefulBackupPointUuid=$currentUuid
		    m_Position=$backupPositionMode
		    m_PrefixDestPath=$backupPrefixDestPath
            lastbackupname=$currentComment
            if [[ -n "${m_default_uuid}" && "${currentUuid}" =~ "${m_default_uuid}" ]]; then
                echo "找到了指定的备份点${currentUuid}" >>$PLOGFILE
                break
            elif [ -n "${m_default_uuid}" ]; then
                echo "${currentUuid}不是指定的备份点${m_default_uuid}，继续下一个" >>$PLOGFILE
                lastUsefulBackupPointUuid=
		        m_Position=
		        m_PrefixDestPath=
                lastbackupname=
            fi
        fi
    fi
    done <"$m_backuplistPath"
    IFS=$IFS_old

    if [ "$lastUsefulBackupPointUuid" = "" ]; then
        echo "can't find a useful backup for restoring"
        exit 6
    fi

    echo "UUID to be restored：${lastUsefulBackupPointUuid}" >>$PLOGFILE
    echo "UUID to be restored：${lastUsefulBackupPointUuid}"

    lastUsefulBackupPointUuid=$(echo $lastUsefulBackupPointUuid | sed 's:<Uuid>::' | tr -d "\n")
    lastUsefulBackupPointUuid=$(echo $lastUsefulBackupPointUuid | sed 's:</Uuid>.*::' | tr -d "\n")
    #echo "lastUsefulBackupPointUuid=$lastUsefulBackupPointUuid"
    lastbackupname=$(echo $lastbackupname | sed 's:<Comment>::' | tr -d "\n")
    lastbackupname=$(echo $lastbackupname | sed 's:</Comment>.*::' | tr -d "\n")
}

restoreAuto() { #还原
    local xxx
    local uuid
    if [ $m_isFactory = true ]; then
    	m_default_uuid="{00000000-0000-0000-0000-000000000000}"
    fi
    getLastUsefulBackupPointUuid
	uuid=$lastUsefulBackupPointUuid
	if [ "${uuid}" = "{00000000-0000-0000-0000-000000000000}" ]; then
		m_isFactory=true
	fi

    #写日志文件
    local m_time=$(date "+%y-%m-%d %H:%M:%S" | tr -d "\n")
    writeLogFile "${m_time},${uuid},4,grub系统还原,,,${lastbackupname}" #grub时只有一键还原，没有增量还原

    restoreDir="${m_mountPath}/snapshots/${uuid}"
    restoreDataPath="${restoreDir}/data"
    if [ $m_Position = true ]; then
	    local prePath=""
	    # if [[ $m_PrefixDestPath =~ ^/data || $m_PrefixDestPath =~ ^/autobackup ]]; then
	    if [[ "x${m_PrefixDestPath}y" != "xy" && "x${m_PrefixDestPath}y" != "x/y" ]]; then
		    prePath="${rootpath}${m_PrefixDestPath}"
	    fi

	    local imgFile="${prePath}/backup/snapshots/${uuid}/data/dst.img"
        local bootDir="${prePath}/backup/snapshots/${uuid}/data/boot"
        echo "imgFile = ${imgFile}"
	    echo "imgFile = ${imgFile}" >> $PLOGFILE
        echo "bootDir = ${bootDir}"
	    echo "bootDir = ${bootDir}" >> $PLOGFILE
	    if [ -e $imgFile ]; then
            local imgPath="${m_mountPath}/imgbackup"
		    mkdir -p $imgPath
		    mount -o loop,ro "${imgFile}" "${imgPath}"
		    sleep 1
		    mount | grep imgbackup >> ${PLOGFILE}
		    if [ ! -e "${imgPath}/boot" ]; then
			    echo "${imgFile} does not mounted on ${imgPath}"
			    exit 9
		    fi
		    restoreDataPath=${imgPath}
	        restoreDir="${prePath}/backup/snapshots/${uuid}"
        elif [ -e $bootDir ]; then
            restoreDir="${prePath}/backup/snapshots/${uuid}"
            restoreDataPath="${restoreDir}/data"
            echo "非压缩备份点${restoreDir}" >> $PLOGFILE
	    else
		    echo "$imgFile does not exist!"
		    exit 7 #备份文件不存在，不能还原系统
	    fi
    fi

    if [ ! -e "${restoreDataPath}/boot" ]; then
        echo "full restore directory not exists!"
        exit 7 #备份文件不存在，不能还原系统
    fi

    if [ "$uuid" = "{$auto_uuid}" ]; then
	    m_isRetainUserData=true
    fi

    echo "Begin to restore efi directory..." >>$PLOGFILE
    echo "Begin to restore efi directory..."
    #额外排除目录或文件
    local excludes=
    if [ -d ${restoreDataPath}/efi ]; then
        rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete ${restoreDataPath}/efi ${rootpath}/boot >/dev/null 2>>$PLOGFILE
        if [ $? -ne 0 -a $? -ne 24 -a $? -ne 23 ]; then
            echo "System restoring failed, please reboot your system!"
            echo "System restoring failed, please reboot your system!" >>$PLOGFILE
            exit 9
        fi
    elif [ -d ${restoreDataPath}/boot/efi ]; then
        rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete ${restoreDataPath}/boot/efi ${rootpath}/boot >/dev/null 2>>$PLOGFILE
        if [ $? -ne 0 -a $? -ne 24 -a $? -ne 23 ]; then
            echo "System restoring failed, please reboot your system!"
            echo "System restoring failed, please reboot your system!" >>$PLOGFILE
            exit 9
        fi
    fi

    echo "Begin to restore other directories..."
    echo "Begin to restore other directories..." >>$PLOGFILE
    #保留用户数据还原
    if [[ x${m_isRetainUserData} = x"true" ]]; then
       echo "保留用户数据还原" >> ${rootpath}/var/log/backup.log
       # 用户数据目录或文件
       if [ -e "${rootpath}/var/lib/biometric-auth" ]; then
	   excludes="${excludes} --exclude=/var/lib/biometric-auth"
       fi
       if [ -e "${rootpath}/data/sec_storage_data" ]; then
           excludes="${excludes} --exclude=/data/sec_storage_data"
       fi
       if [ -e "${rootpath}/etc/passwd" ]; then
           excludes="${excludes} --exclude=/etc/passwd"
       fi
       if [ -e "${rootpath}/etc/shadow" ]; then
           excludes="${excludes} --exclude=/etc/shadow"
       fi
       if [ -e "${rootpath}/etc/group" ]; then
           excludes="${excludes} --exclude=/etc/group"
       fi
       if [ -e "${rootpath}/etc/gshadow" ]; then
           excludes="${excludes} --exclude=/etc/gshadow"
       fi
       if [ -e "${rootpath}/etc/sudoers" ]; then
           excludes="${excludes} --exclude=/etc/sudoers"
       fi
       excludes="${excludes} --exclude=/home --exclude=/root --exclude=/var/lib/AccountsService"
       #下面是域用户相关信息，保留用户数据还原后不退域
       excludes="${excludes} --exclude=/etc/sssd --exclude=/var/lib/sss --exclude=/usr/share/sssd --exclude=/etc/ipa --exclude=/etc/krb5.keytab"
       excludes="${excludes} --exclude=/etc/krb5.conf --exclude=/var/lib/ipa-client --exclude=/etc/nsswitch.conf --exclude=/etc/pam.d --exclude=/etc/hosts"
       excludes="${excludes} --exclude=/etc/hostname --exclude=/etc/hedron --exclude=/etc/kcm --exclude=/usr/hedron/hedronagent --exclude=/etc/.kyinfo --exclude=/etc/LICENSE"
       excludes="${excludes} --exclude=/etc/ssl/certs --exclude=/usr/share/ca-certificates --exclude=/etc/NetworkManager --exclude=/var/lib/pam"
       excludes="${excludes} --exclude=/etc/kim --exclude=/var/lib/kim --exclude=/etc/systemd/system/multi-user.target.wants/kimbackend.service --exclude=/var/lib/polkit-1/localauthority/40-domain.d --exclude=/lib/*/libsss_sudo.so "

       excludes="${excludes} --exclude=/usr/share/applications/kylin-os-installer.desktop"
       excludes="${excludes} --exclude=*/.local/share/applications/kylin-os-installer.desktop"
       excludes="${excludes} --exclude=/etc/xdg/autostart/kylin-os-installer.desktop"

       #如果是990，排除/data；否则，排除/data/usershare
       #if [ x${is_990_9a0} == x"true" ]; then
           excludes="${excludes} --exclude=/data"
       #else
       #    excludes="${excludes} --exclude=/data/usershare"
       #fi
       #如果是出厂备份的还原，还需要保留语言和时区配置
       if [[ ${uuid} = "{${factory_uuid}}" && x${is_990_9a0} != x"true" ]]; then
	   if [ -e "${rootpath}/etc/localtime" ]; then
               excludes="${excludes} --exclude=/etc/localtime"
           fi
	   if [ -e "${rootpath}/usr/share/zoneinfo" ]; then
               excludes="${excludes} --exclude=/usr/share/zoneinfo"
           fi
           if [ -e "${rootpath}/etc/default/locale" ]; then
               excludes="${excludes} --exclude=/etc/default/locale"
           fi
           if [ -e "${rootpath}/usr/share/i18n" ]; then
               excludes="${excludes} --exclude=/usr/share/i18n"
           fi
       fi

       # 系统更新的还原不还原下面目录
       if [ "${uuid}" = "{01234567-0123-0123-0123-0123456789ab}" ]; then
            #excludes="${excludes} --exclude=/var/lib/kylin-system-updater"
            #excludes="${excludes} --exclude=/var/cache/kylin-system-updater"
            excludes="${excludes} --exclude=/var/lib/kylin-system-updater/remain"

       fi
    fi
    # 兼容以前的老备份数据，后面可以尝试去掉此条件的逻辑
    # 出厂还原时，还原文件/etc/uid_list，其它场景不还原:等保四级标准操作系统使用周期内有uid唯一性的要求
    if [ "${m_isFactory}" != "true" ]; then
    	if [ ! -e "${restoreDir}/data/etc/uid_list" ]; then
    		excludes="${excludes} --exclude=/etc/uid_list"
    	fi
    fi
    if [ ! -e "${restoreDir}/data/boot/efi" ]; then
        excludes="${excludes} --exclude=/boot/efi"
    fi
    excludes="${excludes} --exclude=/var/log"
    excludes="${excludes} --exclude=*/backup/snapshots"
    excludes="${excludes} --exclude=/data/security-dir"
    excludes="${excludes} --exclude=/usr/share/plymouth"
    # 还原后仍然保持激活状态
    excludes="${excludes} --exclude=/etc/LICENSE --exclude=/etc/.kyinfo --exclude=/etc/.kyactivation --exclude=/etc/.kyhwid"
    # 还原保留自身
    excludes="${excludes} --exclude=/usr/bin/kylin-backup-daemon --exclude=/usr/bin/backup_mount_fstab --exclude=/usr/bin/restore-system"
    excludes="${excludes} --exclude=/usr/share/initramfs-tools/hooks/kylin-backup-hooks"
    excludes="${excludes} --exclude=/usr/share/initramfs-tools/scripts/init-bottom/kylin-backup"
    excludes="${excludes} --exclude=/usr/share/initramfs-tools/conf-hooks.d/kylin-backup"
    excludes="${excludes} --exclude=/etc/extra_backup_or_restore.conf"

    # 针对opt目录，系统升级时仅备份下面的kylin-os-manager，还原也应该只针对这个目录
    excludes="${excludes} --include=/opt/kylin-os-manager"
    excludes="${excludes} --include=/opt/kylin-os-manager/*"
    excludes="${excludes} --exclude=/opt/*"

    #yi jian huan yuan
    if [ ! -e "${restoreDir}/data/data" ]; then
        #这两行要一致
        echo "rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete --exclude=/data ${excludes}  --exclude-from ${restoreDir}/${PERSONAL_EXCLUDEFILE} ${restoreDataPath}/ $rootpath" >>${rootpath}/var/log/backup.log 2>&1
        rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete --exclude=/data ${excludes} --exclude-from ${restoreDir}/${PERSONAL_EXCLUDEFILE} "${restoreDataPath}/" $rootpath >>${rootpath}/var/log/backup.log 2>&1
    else
        #这两行要一致
        echo "rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete ${excludes} --exclude-from=${restoreDir}/${PERSONAL_EXCLUDEFILE} ${restoreDataPath}/ $rootpath" >>${rootpath}/var/log/backup.log 2>&1
        rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete ${excludes} --exclude-from=${restoreDir}/${PERSONAL_EXCLUDEFILE} "${restoreDataPath}/" $rootpath >>${rootpath}/var/log/backup.log 2>&1
    fi

    if [ $? -ne 0 -a $? -ne 24 -a $? -ne 23 ]; then
        echo "System restoring failed, please reboot your system!"
        echo "System restoring failed, please reboot your system!" >>$PLOGFILE
        exit 9
    fi

    echo "restore other directories end"
    echo "restore other directories end" >>$PLOGFILE

    # 还原额外数据  
	local restoreExtraDataPath="${restoreDir}/extra_data" 
    local PERSONAL_EXARTALFILE=".user_extra.txt"
    if [ -e "${restoreExtraDataPath}" ]; then
        if [ -e ${restoreDir}/${PERSONAL_EXARTALFILE} ]; then
            echo "restore extra data"
            echo "restore extra data" >>$PLOGFILE
            
            #这两行要一致
            echo "rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete --files-from=${restoreDir}/${PERSONAL_EXARTALFILE} ${restoreExtraDataPath}/ $rootpath" >>${rootpath}/var/log/backup.log 2>&1
            rsync -avAXHr --no-inc-recursive --ignore-missing-args --delete --files-from=${restoreDir}/${PERSONAL_EXARTALFILE} "${restoreExtraDataPath}/" $rootpath >>${rootpath}/var/log/backup.log 2>&1

        fi
    fi

    sync

    # TODO : 解决问题：系统更新后，grub系统还原(桌面系统还原没有问题)，然后自动引导不起来，需要手动引导系统
    #       问题1——grub-install命令的--target参数不同架构不一样；
    #       问题2——命令执行报错：failed to register the EFI boot entry: Operation not permitted.
    #       问题3——未知
    #  由于问题不常见，且桌面系统还原没有问题，暂时不修改grub还原部分
    device_boot=$(mount | grep /boot | grep -v /efi | awk '{print $1}')
    device_efi=$(mount | grep /boot/efi | awk '{print $1}')
    echo "device_boot=${device_boot} device_efi=${device_efi}" >>$PLOGFILE
    device_boot=${device_boot#${rootmnt}}
    device_efi=${device_efi#${rootmnt}}
    echo "After chroot: device_boot=${device_boot} device_efi=${device_efi}" >>$PLOGFILE
    if [ "x${device_efi}" = "x" ]; then
        echo "efi partition not mounted, please check if loss vfat type filesystem module"
        echo "efi分区未挂载，请检查内核或initrd中是否缺少vfat文件系统类型模块"  >>$PLOGFILE
    else
        if [ "x${device_boot}" != "x" ]; then
            echo "grub-install -v --force  --boot-directory=/boot/ --efi-directory=/boot/efi/ ${device_boot}"  >>$PLOGFILE
            chroot ${rootmnt} /bin/bash -c "mount -t proc proc /proc"
            chroot ${rootmnt} /bin/bash -c "mount -t sysfs sys /sys"
            chroot ${rootmnt} /bin/bash -c "mount -t devtmpfs devtmpfs /dev"
            chroot ${rootmnt} /bin/bash -c "mount -t devpts devpts /dev/pts"
            chroot ${rootmnt} /bin/bash -c "grub-install -v --boot-directory=/boot/ --efi-directory=/boot/efi/ ${device_boot}"
            if [ $? -ne 0 ]; then
                echo "chroot run 'grub-install' error!"
                echo "chroot run 'grub-install' error!" >>$PLOGFILE
            else
                echo "chroot run 'grub-install' ok!"
                echo "chroot run 'grub-install' ok!" >>$PLOGFILE
                sync
            fi
        fi
    fi
}

#-----------------------------------------------------------------
#--------主程序从这里开始-----------------------------------------

if [ "${rootpath}" = "/" ]; then
    echo "This program is used in boot time"
fi

getBackupInfo
#不加引号报错
if [ "$m_restoreUuid" = "" ] || [ "$m_enabled" = "" ]; then
    echo "May be no backup partation or bootinfo file is not correct!"
fi

mkdir -p ${rootpath}/var/log

echo "参数:" $* >> ${rootpath}/var/log/backup.log
echo "m_isRetainUserData=" $m_isRetainUserData >> ${rootpath}/var/log/backup.log

# 临时关闭安全，因为有些文件安全保护为只读，造成备份还原无法操作
sm_status=$(cat /sys/kernel/security/kysec/sm)
file_protect=$(cat /sys/kernel/security/kysec/fpro)
echo "文件保护状态：${file_protect} sm_status=${sm_status}" >> ${rootpath}/var/log/backup.log
echo 0 > /sys/kernel/security/kysec/sm
echo 0 > /sys/kernel/security/kysec/fpro

if [ $backupORrestore = "--rollback" ]; then
    mountBackup
    mount >>$PLOGFILE
    restoreAuto
    echo "This is rollback"
else
    echo "Not correct command"
fi

echo ${file_protect} > /sys/kernel/security/kysec/fpro
echo ${sm_status} > /sys/kernel/security/kysec/sm
# 还原后需要安全重新打标记，设置如下
echo 0 > /etc/kysec/tmp/.status
echo 0 > ${rootpath}/etc/kysec/tmp/.status

#为了兼容2107版本，还原之后需要用以下两种操作触发全盘打标
sqlite3 ${rootpath}/etc/kysec/db/whlist.db 'update relabel_status set relabel=0';
touch ${rootpath}/.exectl

exit 0
