#!/bin/bash

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2020-present Shanti Gilbert (https://github.com/shantigilbert)
# Copyright (C) 2023 JELOS (https://github.com/JustEnoughLinuxOS)

. /etc/profile

# NOTE: to customize your backups, create a backuptool.conf file in
# /storage/.config like this:

# LOCATIONS=(
#   /storage/.config/retroarch/*
#   /storage/roms/savestates/*
#   /some/other/folder/file.name*
# )

BACKUPFOLDER="/storage/roms/backup"
BACKUPFILE="${BACKUPFOLDER}/${OS_NAME}_BACKUP.zip"
mkdir -p ${BACKUPFOLDER}

DEFAULT=(
    /storage/.config/fancontrol.conf
    /storage/.config/backuptool.conf
    /storage/.cache/bluetooth/*
    /storage/.cache/connman*
    /storage/.config/system/configs/system.cfg
    /storage/.config/ppsspp/*
    /storage/.config/retroarch/*
    /storage/.config/moonlight/*
    /storage/.config/game/*
    /storage/.emulationstation/es_*.cfg
    /storage/.emulationstation/scripts/*
    /storage/.emulationstation/themesettings/*
    $(find /storage/.emulationstation/themes/* -type d -maxdepth 0 -not -path "*es-theme-art-book-next" -not -path "*system-theme")
)

if [ -e "/storage/.config/backuptool.conf" ]
then
    source /storage/.config/backuptool.conf
    if [ ! $? = 0 ]
    then
        WARN="Error loading custom backuptool configs. Using defaults."
        ${DEBUG} && echo "${WARN}"
        logger -t backuptool "${WARN}"
        COMPRESSLOCATIONS=(${DEFAULT[@]})
    else
        COMPRESSLOCATIONS=(${LOCATIONS[@]})
    fi
else
    COMPRESSLOCATIONS=(${DEFAULT[@]})
fi

case "${1}" in
    "restore")
        unzip -o ${BACKUPFILE} -d /
    ;;
    "backup")
        if [ -f ${BACKUPFILE} ]
        then
            TODAY=`date +%y-%m-%d_%H_%M_%S`
            ARCHIVEFILENAME="ARCHIVED_${OS_NAME}_BACKUP-${TODAY}.zip"
            mv ${BACKUPFILE} "${BACKUPFOLDER}/${ARCHIVEFILENAME}"
        fi
        [ -f "${BACKUPFILE}" ] && rm "${BACKUPFILE}"
        zip -9 -r ${BACKUPFILE} \
        ${COMPRESSLOCATIONS[@]}
    ;;
esac
