#!/bin/bash

mount | grep overlay | grep " / " > /dev/null
if [[ $? -ne 0 ]];then
    echo "system is not in overlay mode, can not delete os backup"
    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

do_delete()
{
	overlayx=$1
	
	touch /.overlayup/.delete.flag.$over
	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/
	
	echo "restore succeed, reboot ..."
	reboot
}

if [[ "$backup_name" == "" ]];then
  bash ${SHELL_FOLDER}/osbackuplist
  while true;do
    echo -n "please select the backup you want to delete, 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 "confirm? [Y/N]"
    read confirm
    if [[ $confirm == "Y" || $confirm == "y" ]];then
        echo "oprate succeed, deleting backup will be affected after reboot"
        touch /.overlayup/.delete.flag.$selectindex
		break
    fi

  done
else
  deleted=
  for file in `ls /.overlayup/`;do
    if [[ "${file:0:4}" == "name" && "`cat /.overlayup/$file`" == $backup_name ]];then
        touch /.overlayup/.delete.flag.${file:4}
        deleted=1
    fi
  done
  if [[ "$deleted" == "" ]];then
      echo "the backup of $backup_name does not exist"
      exit 1
  else
      echo "delete backup succeed, work after reboot"
      exit 0     
  fi
fi

