#!/bin/bash

mount | grep overlay | grep " / " > /dev/null
if [[ $? -ne 0 ]];then
    echo "system is not in overlay mode, can not restore os"
    exit 1
fi

if [[ ! -e /.overlayup ]];then
    echo "/.overlayup directory do not exist, exception"
    exit 1
fi

if [[ ! "$(id -u)" == "0" ]];then
    echo "only root user can restore"
    exit 1
fi

backup_name=
for para in "$@";do
    case $para in
        --name=*)
            backup_name="${para#*=}"
            ;;
    esac
done

SHELL_FOLDER=$(cd "$(dirname "$0")";pwd)
source ${SHELL_FOLDER}/osbackuputils

bash ${SHELL_FOLDER}/osbackuplist

do_restore()
{
	overlayx=$1
	
	set_overlayx $overlayx
	if [[ $? -ne 0 ]]; then 
		echo "set backup poing to grub.cfg failed"
		exit 1
	fi 
	
	# rm -rf /.overlayup/upper_now/
	# rm -rf /.overlayup/upper_boot_now/
        touch /.overlayup/.restore.flag
	
	echo "restore succeed, reboot ..."
	reboot
}

if [[ "$backup_name" == "" ]];then
  while true;do
    echo -n "please select one backup to restore, for example 1:"

    read selectindex
    if [[ -z $selectindex ]]; then
        echo "    empty,input nothing,"
        continue
    fi

    if [[ ! $selectindex -gt 0 || ! -f /.overlayup/desc$selectindex ]];then
        echo "    the backup you choose do not exist,"
        continue
    fi

    echo -n "warning: osrestore will lost current state and system will reboot,confirm? [Y/N]"
    read confirm
    if [[ $confirm == "Y" || $confirm == "y" ]];then
        #files=`ls /.overlayup/`
        #for file in $files;do 
        #    if [[ ${file:0:5} == "upper" && ! $file == "upper" && ${file:5} -gt $selectindex ]];then
        #        rm -rf /.overlayup/$file
        #    fi
        #    if [[ ${file:0:10} == "upper_boot" && ! $file == "upper_boot" && ${file:10} -gt $selectindex ]];then
        #        rm -rf /.overlayup/$file
        #    fi
        #    if [[ ${file:0:4} == "desc" && ! $file == "desc" && ${file:4} -gt $selectindex ]];then
        #        rm -rf /.overlayup/$file
        #    fi
        #done
		
		do_restore $selectindex
    fi
  done
else
  for file in `ls /.overlayup/ 2> /dev/null`;do
    if [[ "${file:0:4}" == "name" && "`cat /.overlayup/$file`" == $backup_name ]];then
        backup_id=${file:4}
        do_restore $backup_id
        exit 0
    fi
  done
      
  echo "the backup of $backup_name does not exist"
  exit 1
fi


