#!/bin/sh

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2009-2014 Stephan Raue (stephan@openelec.tv)
# Copyright (C) 2020-present Team LibreELEC (https://libreelec.tv)

. /usr/lib/libreelec/functions

hidecursor

BACKUP_EXTENSION_LIST=".tar .tar.gz .tar.bz2 .tar.xz"
for EXTENSION in $BACKUP_EXTENSION_LIST; do
  BACKUP_FILE=$(find /storage/.restore/ -name "*${EXTENSION}" -print -quit 2>/dev/null)
  [ -n "${BACKUP_FILE}" ] && break
done


if [ -f "${BACKUP_FILE}" ]; then
  echo -e "RESTORE IN PROGRESS\n"
  echo -e "Please do not reboot or turn off your @DISTRONAME@ device!\n"

  StartProgress spinner "Checking backup file... "
    tar tf "${BACKUP_FILE}" &>/dev/null

  if [ $? -eq 0 ]; then
    StopProgress "OK"

    echo -e "\nThis may take some time to complete, please be patient.\n"

    StartProgress spinner "Restoring... "
      rm -rf /storage/.kodi \
             /storage/.cache \
             /storage/.config &>/dev/null
      tar xf "${BACKUP_FILE}" -C / &>/dev/null
      rm -f "${BACKUP_FILE}" &>/dev/null
      sync
      StopProgress "done!"

    echo
    StartProgress countdown "Rebooting in 5s... " 5 "NOW"
  else
    StopProgress "FAILED"

    echo -e "\nBackup file is not valid, or corrupt.\n"

    StartProgress spinner "Removing file to allow normal restart... "
      rm -f "${BACKUP_FILE}" &>/dev/null
      sync
      StopProgress "done"

    echo
    StartProgress countdown "Rebooting in 30s... " 30 "NOW"
  fi
fi

reboot -f
